Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using auto variables for global scope

Tags:

c

auto int a=5;
#include<stdio.h>
int main ()
{
    printf("%d",a);
    return 0;
}

I have read that the scope of automatic variables is within the specified block . In the above program, since the auto variable 'a' is declared outside main function, it should be assigned global scope and be accesible within the main . But, there seems to be an error .

like image 682
itsme.cvk Avatar asked Feb 09 '26 23:02

itsme.cvk


2 Answers

Variables at top-level cannot be auto. They should be either declared static, extern (definition elsewhere) or global (no keyword for that).

This won't compile.

$ echo "auto int c;" > test.c
$ gcc -Wall -c test.c
test.c:1:10: error: file-scope declaration of ‘a’ specifies ‘auto’
like image 154
Fred Foo Avatar answered Feb 12 '26 16:02

Fred Foo


In C, global scope auto variables are not allowed. Per definition they are function-local variable.

like image 34
Jens Gustedt Avatar answered Feb 12 '26 16:02

Jens Gustedt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!