int main()
{
auto status = 203;
auto static const str = "Hello";
auto static const strs = {"Hello", "World"};
return status;
}
From playing around with auto
(and reading some articles), I discovered that it can not be used as a function's return type or as a parameter, but can only be applied on objects.
It works just fine for the first two statements in the above code, but fails for strs
with:
auto.c: In function ‘main’:
auto.c:5:30: error: expected expression before ‘{’ token
5 | auto static const strs = {"Hello", "World"};
| ^
compilation terminated due to -Wfatal-errors.
Why can't the type of strs
be inferred? What other restrictions are there for auto
(except for the two I have mentioned above)?
strs
? The right-hand side doesn't have a type since it isn't an expression.str
,auto
always applies lvalue-to-rvalue conversions to deduce the type.auto
can therefore not deduce an array type. It would be somewhat inconsistent if it was able to deduce an array type forstrs
. Also, since this syntax originates from C++ where the deduction would (unfortunately) be tostd::initializer_list<const char*>
. I think a different choice in C would probably not be made to avoid incompatibility between the two languages."Hello"
is an expression and as such has a type (char[6]
). But{"Hello", "World"}
is not an expression and it doesn't have any associated type.{"Hello", "World"}
could be an initializer list for an array of pointers tochar
, for an array of arrays ofchar
, for a structure containing two members that are pointers tochar
, for a structure containing one member that is a pointer tochar
and one member that is an array ofchar
, among other possibilities.auto
seems underspecified in general. 6.7.1 ought to explain its use and what it is good for to begin with, but does not. 6.7.9 is very vague and leaves a lot unexplained. This was IMO the dumbest and most dangerous feature introduced with C++11 but at least C++ made an effort to explain the keyword's uses in normative text. C23 doesn't even do that. I guess the keyword is good for writing bugs and breaking pre-C23 code but not much else...