Why does auto a=1; compile in C?

2019-01-13 00:48发布

The code:

int main(void)
{
    auto a=1;
    return 0;
}

gets compiled without errors by the MS Visual Studio 2012 compiler, when the file has the .c extension. I have always thought that when you use the .c extension, compilation should be according to the C syntax, and not C++. Moreover, as far as I know auto without a type is allowed only in C++ since C++11, where it means that the type is deduced from the initializer.

Does that mean that my compiler isn't sticking to C, or is the code actually correct in C-language?

标签: c auto c11
7条回答
Deceive 欺骗
2楼-- · 2019-01-13 01:52

In C, and historic dialects of C++, auto is a keyword meaning that a has automatic storage. Since it can only be applied to local variables, which are automatic by default, no-one uses it; which is why C++ has now repurposed the keyword.

Historically, C has allowed variable declarations with no type specifier; the type defaults to int. So this declaration is equivalent to

int a=1;

I think this is deprecated (and possibly forbidden) in modern C; but some popular compilers default to C90 (which, I think, does allow it), and, annoyingly, only enable warnings if you specifically ask for them. Compiling with GCC and either specifying C99 with -std=c99, or enabling the warning with -Wall or -Wimplicit-int, gives a warning:

warning: type defaults to ‘int’ in declaration of ‘a’
查看更多
登录 后发表回答