Search code examples
c++auto

Initializing char array using auto keyword


I have been testing auto keyword and found out strange thing for me. Each letter takes 1 byte(char type), and using auto specifier size of auto variable is 4 bytes no matter what(I wasn't testing very long strings). How can it be explained?

char carray[] = "Some test output";
auto variable = "Some test output";

cout<<"carray: "<<sizeof(carray)<<endl;
cout<<"auto: "<<sizeof(variable);

Solution

  • Because of array-to-pointer decay, variable becomes a const char* (with size of 4, which is somewhat surprising for me - what's your platform?).

    If you want your variable to remain a character array, you might use decltype(auto), like

    decltype(auto) variable = "Some test output"; // sizeof(variable) is 17