簡體   English   中英

退出函數后,為什么此變量值返回默認值?

[英]Why does this variable value return to default value after exiting the function?

我想用國際象棋程序移動騎士。 因此,我在包括main在內的所有函數的頂部定義了這兩個變量( currentRowcurrentColumn )。 (這樣做是因為我希望這些變量作為所有函數的全局變量),如下所示。 因為當騎士移動時,它的位置會改變。 這將是下一步行動的輸入。

我不了解的是,當我調試時,我看到這些變量在函數中發生了變化,但是一旦退出函數,它們就會恢復為默認值(3和4)。

你能告訴我如何解決這個問題嗎? 提前致謝...

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int currentRow=3;
int currentColumn=4;

int main(void){

...
}

int checkIsEmptyandMoveAccordingly(int moveNumber, int currentRow, int currentColumn){

   if (chessBoard[currentRow+vertical[moveNumber]][currentColumn+horizontal[moveNumber]]==0   && currentRow+vertical[moveNumber]>=0 && currentColumn+horizontal[moveNumber] >=0   ){   //if empty,move to new location

         currentRow+=vertical[moveNumber];
         currentColumn+=horizontal[moveNumber];
         printf("Move randomised to: %d\n", moveNumber);
         printf("Knight has moved to chessBoard[%d][%d].\n",currentRow,currentColumn);
         count++;
         printf("Move count is %d.\n",count);
         chessBoard[currentRow][currentColumn]=1;
         if(!checkIsAroundFUll()){
            moveNumber=randomiseMovement();
            return moveNumber;
         }
         else   { 
              printf("ALL TARGET SPACES ARE VISITED BEFORE. KNIGHT CAN NOT MOVE\n PROGRAM WILL BE TERMINATED!!!\n");
              return -1;
         }
   }

   else if (chessBoard[currentRow+vertical[moveNumber]][currentColumn+horizontal[moveNumber]]==1)  {                                                                                                                                                    //if not empty, randomise again

         printf("Knight CAN NOT MOVE! Target SPACE IS OCCUPIED\n");
         if(!checkIsAroundFUll()){
            moveNumber=randomiseMovement();
            return moveNumber;
        }
         else   { 
              printf("ALL TARGET SPACES ARE VISITED BEFORE. KNIGHT CAN NOT MOVE\n PROGRAM WILL BE TERMINATED!!!");
              return -1;
         }

   }

   else {
         printf("OUT OF BOUNDS!! CAN NOT MOVE. TRYING ANOTHER MOVEMENT");
         if(!checkIsAroundFUll()){
            moveNumber=randomiseMovement();
            return moveNumber;
        }
         else   { 
              printf("ALL TARGET SPACES ARE VISITED BEFORE. KNIGHT CAN NOT MOVE\n PROGRAM WILL BE TERMINATED!!!");

              return -1;
         }
   }
}

int currentRow, int currentColumn在函數參數列表中,因此它們是局部變量。 他們隱藏了具有相同名稱的全局名稱。

您的函數有新變量currentRow和currentColumn聲明為該函數的參數。 如果要更新全局變量,請刪除這些參數(並且在調用函數時不要傳遞它們),您應該會看到全局更新。

您正在做的事情正在遮蓋全局變量。 啟用正確的編譯器警告(具體取決於編譯器),系統將告知您此錯誤。

如果使用gcc,請嘗試使用-Wall -Werror進行編譯。

您的功能是更改本地副本。 當您將它們傳遞給函數時,它們將按值傳遞,函數將創建本地副本,並且本地范圍將覆蓋全局范圍。 如果要引用全局變量,請不要將其傳遞到函數中,而應從那里訪問它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM