Update (int) variable in C inside a function [duplicate]
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?
Solution 1:
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;
}
Solution 2:
C is a pass by value language. The simplest approach to accomplish what you want is to pass a reference to the variable you need 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 up on pointers to fully understand the code if you are just beginning with C programming. In the example code, instead of passing the value of 'stage', you pass the location where the value of 'stage' is stored. The function can then modify the contents in the location.
Solution 3:
C function arguments are pass-by-value. This means that instead of passing a reference to stage
you are passing the value stored in it. The update you do the in changeStage
function then only applies to the copy that has been 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 to take the address of stage
and pass that to the function. The stage_p
argument will then point to the int in the main.
*stage_p
causes it to use the value pointed to by stage_p
, which is stage
in the main in your case.
Further reading
Solution 4:
You are not modifying the original stage
variable, but only modifying an local copy inside changeStage
function.
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 learn more basic concepts of C language. Pointer is an very important feature in C language.
Solution 5:
Correct, you need to pass the pointer if you wish to change the value of the variable in main() or you can create it as global variable, that way it's accesable both in functions and in main.
static int stage = 0;
void changeStage(){
stage = 1;
}
main(){
int score = 0;
...
..
.
while(stage!=0){
//if snake hits wall
changeStage();
}
}