I've run into the following example where the auto declaration defaults to int instead of long:
#include <stdio.h>
int main(int argc, char **argv)
{
auto i = 999999999999999;
// long i = 999999999999999;
printf("i = %ld\n",i);
return 0;
}
When I compile this code, gcc indeed gives a relevant warning that i
is actually an int
:
$ gcc -o main main.c
main.c: In function ‘main’:
main.c:4:10: warning: type defaults to ‘int’ in declaration of ‘i’ [-Wimplicit-int]
auto i = 999999999999999;
^
main.c:4:14: warning: overflow in implicit constant conversion [-Woverflow]
auto i = 999999999999999;
^~~~~~~~~~~~~~~
main.c:6:19: warning: format ‘%ld’ expects argument of type ‘long int’, but argument 2 has type ‘int’ [-Wformat=]
printf("i = %ld\n",i);
~~^
%d
But I'm wondering why gcc's lexical scanner didn't label 999999999999999
as being long when it has all the information to do so? Here is the output of the program:
$ ./main
i = 2764472319
EDIT:
Here is the output of the correct answer (from @Yang) with g++:
$ g++ -o main main.c
$ ./main
i = 999999999999999
And another option for doing it:
$ cp main.c main.cpp
$ gcc -std=c++11 -o main main.cpp
$ ./main
i = 999999999999999
If you want type inference, auto
is a C++ feature. Could you try compiling with g++ instead?
In C and C++98/C++03, auto is a redundant keyword meaning "automatic variable." So in your example, i
is a variable with no explicit type which is therefore treated as an int
(but C99 and later requires a diagnostic).