Update (int) variable in C inside function

I am trying to write a function that changes the screen in my simple C snake game.

main(){ int stage = 0; ... .. . while(stage!=0){ //if snake hits wall changeStage(stage); } } 

function:

 void changeStage(int stage){ stage = 1; } 

This code does not update the code, it will continue to work. What is wrong with my code?

+7
c
source share
5 answers

stage is passed by the value of changeStage . stage = 1 only changes the local stage value in changeStage , not the stage value in main . Instead, you must pass a pointer:

 while (stage != 0) { changeStage(&stage); } void changeStage(int *stage) { *stage = 1; } 
+12
source share

C is the password by value. The easiest way to accomplish what you want is to pass a reference to the variable you want to change. For example:

 void changeStage(int *stage){ *stage = 1; } main(){ int score = 0; int stage = 0; ... .. . while(stage!=0){ //if snake hits wall changeStage(&stage); } } 

Note. You may need to read the pointers to fully understand the code if you are just starting out with C programming. In the code example, instead of passing the value of "stage", you pass in the place where the value of "stage" is stored. The function can then change the content in the location.

+6
source share

C function arguments are passed by value. This means that instead of passing the stage reference, you are passing the value stored in it. The update that you perform in the changeStage function then only applies to the copy that was made.

If you want to update a variable in another function, you will need to pass a pointer to it.

 void changeStage(int* stage_p){ *stage_p = 1; } int main() { //... while(stage!=0){ //if snake hits wall changeStage(&stage); } } 

&stage says it takes the address of stage and passes it to the function. The stage_p argument stage_p then point to int in the main.

*stage_p forces you to use the value specified in stage_p , which stage is mainly in your case.

Further reading

+2
source share

You do not change the original variable stage , but only change the local copy inside changeStage .

You need to use a pointer:

 void changeStage(int* stage) { *stage = 1; } 

using the function:

 while (stage != 0) { // if snake hits wall changeStage(&stage); } 

You need to learn more basic concepts in C. Pointer is a very important function in C.

+2
source share

That's right, you need to pass a pointer if you want to change the value of the variable in main (), or you can create it as a global variable, so it will be available both in functions and in the main.

 static int stage = 0; void changeStage(){ stage = 1; } main(){ int score = 0; ... .. . while(stage!=0){ //if snake hits wall changeStage(); } } 
+1
source share

All Articles