【问题标题】:If statement in cases not working/being reached如果在不工作/未达到的情况下声明
【发布时间】:2015-02-10 16:16:48
【问题描述】:

我目前有一个继续获取输入的程序,它最初将 b 的值设置为 TRUE(即 b = 1)。然后 switch 语句启动,将 c 的值设置为 TRUE(即 c = 1)。用户的下一个输入将 b 的值设置为 FALSE,但由于某种原因从未到达第一个 if 语句,因为行 "mvprintw(22,24,"It has reached it");" 从未打印在我的屏幕上,尽管事实上 b 的值为 false (b = 1),现在 c 的值为真 (c=1)。

我尝试过使用嵌套的 if 来代替 case,但这会使事情进一步复杂化,而且坦率地说是行不通的。非常感谢您对此事的任何意见!

int moveC(int y, int x, int b, int i)
    { //first input from user, b is True, so first case occurs
      //second input from user, b is false, so second case occurs, however, the if first if statement is never reached, but the second one is
        int c = FALSE;

        switch(b)
        {
             case TRUE:
                 c = TRUE; //this part is first reached from initall user input
                 refresh();
                 mvprintw(26,26,"value of c is... %d",c);
                 break;

             case FALSE:
                 if(c == 1) //this part is never reached, even though the second user input is (b = 0 i.e false, and c = 1, i.e true)
                 {
                      mvprintw(22,24,"It has reached it");
                      mvprintw(y,x+7,"^");
                      refresh();
                      break;
                 }

                 else if(c == 0) //this if statement is always used even if c is not zero
                 {
                    mvprintw(y,x,"^");
                    refresh();
                    break;
                 }

【问题讨论】:

  • 请发布一个完整的可编译示例。
  • 在 C 中用精确值表示非假布尔值通常是一种不好的做法。 "TRUE" 非零; “FALSE”在 C 语言中为零,但“TRUE”的开关值只是(我假设)您通过那个令人困惑的宏定义在某处定义的任何值。使用枚举、使用标志、使用常量,但不要在 C 中使用 TRUE 和 FALSE。
  • @mpez0 我也是这么想的,用if (booleanValue != 0)if (booleanValue == 0)就行了。在switch 中使用FALSETRUE 是没用的。

标签: c user-interface if-statement int case


【解决方案1】:

moveC()你声明

int c = FALSE;

这使它成为驻留在堆栈中的自动变量,因此每次调用时,c 都会再次创建并使用FALSE 初始化,而case TRUE 中的条件c == 1 永远不会为真。如果你想在moveC() 的第二次调用中获得你在第一次调用中分配的值,你必须声明它

static int c = FALSE;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-17
    • 1970-01-01
    • 2020-05-21
    • 1970-01-01
    • 2011-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多