Hi

I have a sequence that I want to put into a seperate function:
The variables I want to take into that function and back to the main function are declared globally.

declaring the function and the testing variable:

void sanction ();
int test[10];

my main function:

int main(int argc, char *argv[])
{
 
test[10] = 10;
printf ("in main: 10 = %d\n", test[10]);     
sanction ();    
printf ("in main after adding: 10 = %d\n", test[10]);  
 
return (0);
}

the separate function:

void sanction( void )
{
printf ("in sanction: 10 = %d\n", test[10]); 
test[10] = test[10] + 1;
}

output:
in main: 10 = 10
in sanction: 10 = 10
in main after adding: 10 = 11

So everything works like it should, but why?
I thought the void ment no variable-values are taken to the separate function and none are returned.
I just want to be sure that when I use this with the actual code, I'm not making any mistakes.

thx

Recommended Answers

All 5 Replies

>>I thought the void ment no variable-values are taken to the separate function and none are returned.

It does mean that -- and the function is working as expected. But the void does NOT mean the function can't change global data.

>>test[10] = test[10] + 1;
array test only has 10 elements, numbered 0, 1, 2, 3, ... and 9. There is no 10th element number as you are attempting to use, so it is writing outside the bounds of the array.

Yes, to implicitly set the functions argument list to none, you use void. you use void to say there is no return type, or return therefore.

Good luck, LamaBot


>>test[10] = test[10] + 1;
array test only has 10 elements, numbered 0, 1, 2, 3, ... and 9. There is no 10th element number as you are attempting to use, so it is writing outside the bounds of the array.

Dammit, I actually know that. LOL

Thx guys

And more using global variables is not a good idea, because of the above reasons. The value of the variable can be changes outside the function.

Why use array only for using a single element in an array. You could have just declared a single int variable.

ssharish2005

And more using global variables is not a good idea, because of the above reasons. The value of the variable can be changes outside the function.

Why use array only for using a single element in an array. You could have just declared a single int variable.

ssharish2005

Maybe because he's testing... ;)

During development a good programmer always writes test code and uses the same structures he's going to use in the finished program to make sure the concepts work.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.