1

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
OrenIshShalom
  • 5,974
  • 9
  • 37
  • 87
  • Note: when or if you compile this as C++ code, the format specification in the `printf` is non-portable, because the type chosen then depends on the number ranges of the built-in types for that compiler. – Cheers and hth. - Alf Aug 20 '18 at 04:25
  • Compile with `-pedantic-errors` if you don't want non-standard C such as `auto i` to compile. Implicit int was removed from the language 20 years ago. Also, you should not use `auto` in any flavour of these languages. In C++ after 2011 this keyword creates a massive type-safety hazard, creating subtle but severe bugs. Just never use the keyword in C or C++. – Lundin Aug 20 '18 at 06:56

1 Answers1

5

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).

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Yang
  • 7,712
  • 9
  • 48
  • 65