0
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)?

6
  • What type would you expect for strs? The right-hand side doesn't have a type since it isn't an expression. Commented May 9 at 11:21
  • 1
    As you can see with 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 for strs. Also, since this syntax originates from C++ where the deduction would (unfortunately) be to std::initializer_list<const char*>. I think a different choice in C would probably not be made to avoid incompatibility between the two languages. Commented May 9 at 11:33
  • 1
    "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. Commented May 9 at 11:36
  • 1
    {"Hello", "World"} could be an initializer list for an array of pointers to char, for an array of arrays of char, for a structure containing two members that are pointers to char, for a structure containing one member that is a pointer to char and one member that is an array of char, among other possibilities. Commented May 9 at 11:42
  • 1
    C23 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...
    – Lundin
    Commented May 13 at 9:44

0

Browse other questions tagged or ask your own question.