编译器忽略我的else语句

时间:2014-04-18 12:25:00

标签: c

我正在用C进行生活游戏。我正在检查一个单元格是否存活(使用DEAD或ALIVE的typedef调用状态)然后检查其邻居的事情。如果它已经死了,我会检查它是否应该生活在下一代。 问题是它不起作用,当我在gdb中调试程序时,似乎忽略了我的else语句。 这是我的代码的相关部分:

#include <stdio.h>
#include <stdlib.h>
#define maxHeight 10
#define maxWidth 10
#define maxGenerations 100
typedef enum { DEAD, ALIVE } state;
void nextGeneration(state[][maxHeight][maxWidth], int, int, int);
int numberOfNeighbours(state[][maxHeight][maxWidth], int, int, int);
void printGeneration(state[][maxHeight][maxWidth], int, int, int);
void nextGeneration(state board[][maxHeight][maxWidth], int requestedGeneration, int boardHeight, int boardWidth)
{
        int h;
        int w;
        int currentNumOfNeighbours;
        for(h = 0; h < boardHeight; h++)
                for(w = 0; w < boardHeight; w++)
                {
                        currentNumOfNeighbours = numberOfNeighbours(board, requestedGeneration, h, w);
                        if(board[requestedGeneration][h][w] == ALIVE)
                        {
                                if(currentNumOfNeighbours == 2 || currentNumOfNeighbours == 3)
                                {
                                        board[requestedGeneration - 1][h][w] == ALIVE;
                                }
                        }
                        else
                        {
                                if(currentNumOfNeighbours == 3)
                                        board[requestedGeneration - 1][h][w] == ALIVE;
                        }
                }
}
你能告诉我什么是错的吗? 感谢。

1 个答案:

答案 0 :(得分:6)

如果您正在使用优化进行编译,编译器可能会通过从输出中完全删除它来优化它:

if(currentNumOfNeighbours == 3)
    board[requestedGeneration - 1][h][w] == ALIVE;

...因为它没有实际效果。你可能意味着:

if(currentNumOfNeighbours == 3)
    board[requestedGeneration - 1][h][w] = ALIVE;

...使用分配(=)代替比较(==)。即使它没有把它拿出来,它实际上并没有做任何事情。