-10
int main()
{
    extern long long a;
    a=100000000000; //10 raised to power 11
    printf("%lld",a);
    return 0;
}
int a;

Output: 100000000000

int a means definition, which will allocate 4 bytes to variable a, but extern long long a is declaration that specifies variable type and has nothing to do with memory allocation. So if I assign a value 10^11 to a(4 bytes big), shouldn't it cause overflow?

1 Answers1

0

Yes, it does cause overflow. Luckily your program is short enough that you didn't notice the damage.

Your code writes 8 bytes into a 4 byte variable. This will scribble on whatever follows a in memory. In your case there are no declarations after a, so it probably wrote over free space, but that's not guaranteed. Whatever, it appears that nothing critical depended on that memory for successful completion of your program.

Some compilers may be able to detect this, but some will not. In the general case, where a is declared in a different source file, this is undetectable. This is why it is good practice to put extern declarations in a header file, and then include that header in the source file that declares the real variable, as well as the source files that use it; that way the compiler gets a chance to check the declarations match.

ams
  • 24,923
  • 4
  • 54
  • 75