-
Global space
I was just wondering if i can expect anything bad from the following code, or whether it is just bad programming practice
Code:
#include <stdio.h>
#include <stdlib.h>
const int RUNNING = 1;
int correct = 0, wrong = 0;
most notably the last line.
also how do i declare these - the last line - in main and have all my functions access them? do i need to use extern or is there another way? and why does it give me an error msg when i do try to have a function call it from main()?
thanks.
-
Just pass them as parameters to your functions. If the function will be changing the value, you'll need to pass a pointer to the variable.
-
You actually want correct and wrong to have the same value? I take it you are not using these as some sort of switch.
There is a way for your functions to have those values. Pass them as arguments.
Could you post a little more code to see what you have going on?
-
no, no they are not constants. I'm using them to see how many answers a user has right and wrong. However I want to declare them once and then call them in ANY function called from main. is ther a way for this, aside maybe from extern.
Thanks.
-
1) Use globals, as you've done:
Code:
#include stuff here
int myglobal;
void fun( void )
{
myglobal = 10;
}
void showglobal( void )
{
printf("myglobal is %d", myglobal );
}
int main( void )
{
myglobal = 4;
showglobal();
fun();
showglobal();
myglobal--;
showglobal();
return 0;
}
That's a poor way to do it. But some times, used sparingly, it works out ok.
2) Pass the variable via function calls:
Code:
#include stuff here
void somefunction( int x )
{
printf("x is %d\n", x );
}
void someotherfunction( int *x )
{
printf("x is %d, ", *x );
*x = 234;
printf("but now it's %d!\n", *x );
}
int yetanotherfunction( void )
{
printf("Changing your variable via return value...\n");
return 1034;
}
int main( void )
{
int myvariable = 0;
somefunction( myvaraible ); /* available, but won't be modified */
printf("myvariable is %d\n", myvariable );
someotherfunction( &myvariable ); /* available, can be modified */
printf("myvariable is %d\n", myvariable );
myvariable = yetanotherfunction( ); /* modified by the return value */
printf("myvariable is %d\n", myvariable );
return 0;
}
Enjoy.
Quzah.
-
Thanks guys, I used it as a global variable first, but i've heard it said that globals should be used sparingly - if at all. However I find it annoying to pass them as parameters to the functions I need them to work with, i have like 6 or seven and yeah i have to write it only once in those functions but it is still redundant. know what i mean.:)