-
another noob question
Howdy agin,
I am onto scope and storage classes now, My question is if i declare a global variable in 1.c and want to use it in 2.c do I have to use the extern specifier? I am just not understanding how the use an allusion.
Code:
int x = 0; /*global variable */
extern int y; /* an allusion to a global variable */
when they say an allusion, do they mean it just mirrors over?
Thank you agin for your time.
-
Yes, you do.
The compiler does not see the contents if 1.c, so for 2.c to actually use variables in 1.c, the compiler must be aware of those variables.
So to do that, we tell the compiler that these variables exist by declaring them exactly as they are defined in the other source file (without initializing them) and slapping "extern" before them.
But you do know that globals variables are dangerous, yes?
-
Yes, I have been reading the boards here alot, and know that global vairables and gets is bad :O)
I just figured that to really know C, i shouldn't skip over the parts that are bad, know how to use them but dont.
Thank you very much for the fast answer!!!!
-
Another noob question if anyone has the time.
I understand why y increase's becase it is permenant (static) but why wouldnt x increase also?
Code:
#include <stdio.h>
main() {
int i;
for (i=0; i<5; i++) {
int x = 0;
static int y = 0;
printf("x=%d, y=%d\n", x++, y++);
}
return (0);
}
-
No, because x incremented AFTER it's printed by printf (postfix). Then x is destroyed since it goes out of scope and reinitialized to 0.
And main returns int.