【问题标题】:Print statement in if, switch and while condition of cc 的 if、switch 和 while 条件中的 print 语句
【发布时间】:2020-05-01 10:58:01
【问题描述】:

有人能解释一下为什么代码打印的是 "HelloWorld" 而不是 "HelloWorldThere" 吗?另外为什么它打印任何东西,因为 if 或 switch 语句中没有条件?代码如下:

#include <stdio.h>

int main()
{
    int a, b;

    if(printf("Hello"))
        switch(printf("World"))
            while(printf("There"))
            {
                return 0;
            }
}

【问题讨论】:

  • 您可能想了解printf returns 的内容。
  • 还有关于switch 的声明……你的代码完全是一派胡言。
  • 关于switch:“如果表达式的计算结果与以下任何一种情况都不匹配:标签,并且默认值:标签不存在,则不会执行任何开关体。” -- 没有case 标签,所以没有匹配表达式,也没有default 标签,所以没有任何反应。
  • 我已经专业地编写 C 语言近 20 年了,但从未意识到这一点:stackoverflow.com/questions/29023601/…。 (编辑以提供更好的链接)
  • @EdHeal: Yes, it compiles and runs,并产生 OP 描述的输出。

标签: c if-statement while-loop switch-statement printf


【解决方案1】:

非常简单:printf("Hello") 返回 5(写入的字符数)。 5 不是 0,因此对于 if 而言,它被认为是“真”,因此 printf("World") 也返回 5,开关查找 case 5:,没有找到,然后停在那里。

【讨论】:

    【解决方案2】:

    首先,让我们考虑一下函数printf 返回的内容。来自 C 标准

    3 printf 函数返回传输的字符数,或者 如果发生输出或编码错误,则为负值。

    所以这个if语句的条件

    if(printf("Hello"))
    

    评估为真,因为printf() 返回一个非零值。

    然后这个switch声明

    switch(printf("World"))
    

    被评估。

    现在让我们考虑switch 语句的工作原理。来自 C 标准

    4 switch 语句使控制跳转到、进入或越过 作为 switch 主体的语句,取决于 a 的值 控制表达式,并在存在默认标签和 开关体上或开关体中的任何大小写标签的值。案例或违约 标签只能在最近的封闭开关内访问 声明。

    由于switch 语句的主体语句没有标签(包括默认标签),因此控件通过主体语句传递。即while语句(即switch语句的主体语句)没有被执行。

    如果您想获得预期的结果,例如插入标签default

    #include <stdio.h>
    
    int main()
    {
        if(printf("Hello"))
            switch(printf("World"))
                default: while(printf("There"))
                {
                    return 0;
                }
    }
    

    在这种情况下,程序输出是

    HelloWorldThere
    

    或者使用空语句作为switch语句的主体语句。

    #include <stdio.h>
    
    int main()
    {
        if(printf("Hello"))
            switch(printf("World")); // <==
                while(printf("There"))
                {
                    return 0;
                }
    }
    

    【讨论】:

    • 为什么添加分号后程序会打印“HelloWorldThere”?
    • @ChinmayVemuri 现在 switch 语句的主体语句是一个 nul 语句。所以while语句是一个单独的语句,在switch语句之后执行。
    • 哦!现在我懂了。感谢您的回复!
    猜你喜欢
    • 1970-01-01
    • 2016-03-02
    • 2018-09-20
    • 1970-01-01
    • 2013-04-13
    • 2016-02-29
    • 1970-01-01
    • 2019-04-08
    • 2020-08-19
    相关资源
    最近更新 更多