首页 > 解决方案 > 否则如何解释它后面的 if 语句?

问题描述

我有一段 C 代码,我想了解程序中的第一个 else 是如何解释它后面的 if 的。通常在 if-else 连词中,当 if 中的条件为 false 时,程序执行 else 之后的语句,当 else 没有花括号时。在下面,else 后面没有大括号,所以我的问题是:else 是否解释“if(prefer>=5) { printf("Buya");printf("也许事情会很快好转!\n") ;}" 作为单个语句,类似于 " else printf("这是上述 else 的替换语句");" 建造?

或者 if-else if 连词还有另一种逻辑?例如,else 只激活“if(prefer>=5)”,如果条件为真,则执行花括号中的内容?

C语言的完整代码如下。先感谢您。

  #include <stdio.h>

    int main()

    {

        int prefer=2;

        if (prefer >= 8)
        {
            printf("Great for you!\n");

            printf("Things are going well for you!\n");
        }
        else if(prefer>=5)
        {
            printf("Buya");
            printf("Maybe things will get even better soon!\n");
        }
         else if(prefer>=3)
        {
            printf("Bogus");
            printf("Maybe things will get worst soon!\n");
        }
        else
        {
            printf("Hang in there--things have to improve, right?\n");
            printf("Always darkest before the dawn.\n");
        }
        return 0;
    }

标签: cif-statement

解决方案


这是一个更括号的版本,应该解释这一点:

if(prefer >= 8)
{
    ...
}
else
{
    if(prefer >= 5)
    {
        ...
    }
    else
    {
        if(prefer >= 3)
        {
            ...
        }
        else
        {
            ...
        }
    }
}

else if(condition) ...没有什么特别的。它相当于else { if(condition) ... }


推荐阅读