Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update (int) variable in C inside a function [duplicate]

Tags:

c

I'm trying to write a function that changes 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 keep on running. What is wrong with my code?

like image 662
user3589718 Avatar asked May 15 '14 00:05

user3589718


1 Answers

stage is passed by value to changeStage. stage = 1 only changes the local value of stage in changeStage, not the value of stage in main. You have to pass a pointer instead:

while (stage != 0) {
    changeStage(&stage);
}

void changeStage(int *stage) {
    *stage = 1;
}
like image 163
univerio Avatar answered Oct 20 '22 22:10

univerio