C:尝试声明变量会导致未声明的变量错误

时间:2013-02-23 07:56:55

标签: c variable-declaration undeclared-identifier

我刚刚开始编写一个小编程项目,而且我对未声明的内容有一个相当常见的错误:

MP_HighLevelData.c:230:15: error: ‘RemovedUser’ undeclared (first use in this function)

以为我刚忘记申报变量,我一直走到源文件中的那一行,发现错误指向这行代码:

User *RemovedUser;

奇怪,我不能声明一个新变量,因为它不存在?我确定这段代码没有特别错,所以这里有一个更完整的代码片段。我真的很想知道我做错了什么。

void RemoveUserFromGameRoom(User *User) {

  if (User->GameRoom != NULL) {
    GameRoom *GameRoom = User->GameRoom;

    if (GameRoom->Owner == User) {

      // We should delete the whole game room, since the owner is leaving and a new owner isn't chosen automatically
      while (GameRoom->UsersHead != NULL) { // Awesome way of looping while there are users left in the room
        // We need to get rid of all the users in this game room, including the owner, before we can remove it
        User *RemovedUser;
        RemovedUser = GameRoom->UsersHead->User;
        DeleteUserPtrFromGameRoom(GameRoom->UsersHead); // Remove reference to the user from the game room
        RemovedUser->GameRoom = NULL; // Remove reference to the game room from the user (needs to be set afterwards, whoops)
      }

      // All the users have been kicked out, now we can take care of the game room
      FreeRIDfromGameCategory(GameRoom->RID, User->GameCategory);
      ClearGameRoomName(GameRoom);
      DeleteGameRoomFromGameCategory(GameRoom, User->GameCategory);

    } else {
      UserPtr *UserPtr = GameRoom->UsersHead;

      while (UserPtr != NULL) {
        if (UserPtr->User == User) {
          DeleteUserPtrFromGameRoom(UserPtr);
          User->GameRoom = NULL;
          break;
        }

        UserPtr = UserPtr->next;
      }
    }

  }

}

1 个答案:

答案 0 :(得分:2)

通常,当面对“类型”或“类型变量”的决定时,编译将始终假定为“类型变量”,这就是在对象工作时访问User的原因。

然而,与此同时,声明类型为User的新对象无法工作,因为对于编译器而言,这是一个变量,而不是一个类型。

简而言之:将变量User重命名为除类型名称之外的任何内容(例如UserObject或其他内容),并且您的代码在这方面应该可以正常运行。

为了澄清,这是我建议的修复:

void RemoveUserFromGameRoom(User *myUser) {

    if (myUser->GameRoom != NULL) {
        GameRoom *GameRoom = myUser->GameRoom;
        //More code to come
    }
    //Some more code
 }