无论输入什么输入,If语句的主体都会运行

Tob*_*non -2 c if-statement

我有一种感觉,这将是一个非常简单的错误,但无论我在程序中输入什么字符,仍然会显示"帮助屏幕".我一直在寻找如何修复一段时间并且不能破解它,正如我所说,我有一种感觉它将是非常愚蠢和简单的东西.我对C没有多少经验,所以对任何业余错误都有任何帮助.哪些符号用于分配,哪些符号用于C中的比较?(=和==)

int initialSelection(){
printf( "                                Welcome to Anagramania!\n");
printf( "Please press (s) to start or (h) to view the help screen\n");
initialChoice = getchar();
    if (initialChoice = 'h'){ //Display help screen
        system("cls");
        printf( "                                Anagramania Help Screen\n");
        printf( "Welcome to Anagramia, created by Toby Cannon. There are three levels of difficulty in this game, easy, medium, or hard! How good do you think you are? Once you start the game you will see some jumbled letters on the screen. You're job is to guess what word these letters have come from! There is 20 words in each game, and you can review your game at the end. \n Good luck!\n");
            getch(); //wait for user input
            system("cls"); //Clear the console
        }
}
Run Code Online (Sandbox Code Playgroud)

T.J*_*der 7

=分配,所以你的代码所做的是分配 'h'initialChoice,然后测试结果,这是值'h'(是赋值表达式的值分配的值).最终测试结果为true,因此if执行了该实体.

==是平等比较.所以:

if (initialChoice == 'h'){
// Note -----------^
Run Code Online (Sandbox Code Playgroud)

任何体面的编译器都应该有"lint"功能,当你这样做时会发出警告.(在文档中搜索"警告".)

  • @tema:"因为赋值成功而返回true"这无所谓!在没有导致程序终止的情况下,对于左值的简单指定在运行时会失败.所以也没有理由在成功和不成功的任务之间有所区别.这个评估为真的唯一原因是,因为通过语义规则,最终的条件是(如前所述)`'h'`什么是`!= 0`. (2认同)