dimanche 31 janvier 2016

Why does auto in `auto s = "abc"` yield char pointer instead of char array?

This program

#include <iostream>

int main() {
    auto s = "Hello, world!\n";
    decltype("Hello, world!\n") t = "Hello, world!\n";
    std::cout << sizeof s << ", ";
    std::cout << sizeof t << ", ";
    std::cout << sizeof "Hello, world!\n" << '\n';
    return 0;
}

prints

4, 15, 15

This suggests that the type of s is char *. This feels wierd considering that the type of the string literal and t is char [15].

Why doesn't this program print 15, 15, 15 instead?

Why does auto declare a pointer type instead of an array type when assigned to a string literal?

Aucun commentaire:

Enregistrer un commentaire