shafeeq
shafeeq

Reputation: 143

Does values of global variable changes if they are updated in function?

actually i have written this code but it isnt working.help me plz.

unsigned short checkCollisionOrFood(unsigned short rowHead,unsigned short colHead)
/*this the functionother then main function where i am changing value of "rowHead",but on checking it remain same*/
{
if(turn==0){
    if(address[colHead]&(1<<((rowHead+1)%8))){
        if(((int)(address[(colHead+7)%8]&(1<<(rowHead+1)%8))
           +(int)(address[colHead]&    (1<<(rowHead+2)%8))
           +(int)(address[(colHead+1)%8]&(1<<(rowHead+1)%8)))>1) return -1;
        else{
            rowHead=(rowHead+1)%8;//this value of rowHead is not getting change.
            return 1;
            } 
        } 
    }

the variables "turn","rowHead","colHead" are global variables. Now after modifying this code as per instruction of Daniel Fischer,it is

unsigned short checkCollisionOrFood()
{
if(turn==0){
    if(address[colHead]&(1<<((rowHead+1)%8))){
    if(((int)(address[(colHead+7)%8]&(1<<(rowHead+1)%8))
    +(int)(address[colHead]&(1<<(rowHead+2)%8))
    +(int)(address[(colHead+1)%8]&(1<<(rowHead+1)%8)))>1) return -1;
      else{
          rowHead=(rowHead+1)%8;
          return 1;
          } 
          }
}

Upvotes: 0

Views: 2302

Answers (2)

Daniel Fischer
Daniel Fischer

Reputation: 183978

Your function parameters

unsigned short checkCollisionOrFood(unsigned short rowHead,unsigned short colHead)

shadow the global (file scope, actually) variables of the same name, so in the function, you only change the copies of the passed arguments, that has no effect outside the function. In the function, you cannot access the shadowed global variables (without some gymnastics).

The point of global variables is that they (nor pointers to them) need not be passed as arguments, since they can be accessed without that.

Upvotes: 4

Alex
Alex

Reputation: 10136

When you pass variables to function, they are passed by value. That means, that the function has it's own copy of the variable and you can manipulate by variable without modifying initial variable, that was passed.

If you want to modify the value of the global variable, you should not have parameters with the same name or local variables. So, your function supposed to be:

unsigned short checkCollisionOrFood();

Upvotes: 1

Related Questions