Chi*_*uri -3 c printf if-statement while-loop switch-statement
有人可以解释为什么代码打印 "HelloWorld" 而不是 "HelloWorldThere" 吗?另外,为什么它会打印任何内容,因为 if 或 switch 语句中没有条件?这是代码:
#include <stdio.h>
int main()
{
int a, b;
if(printf("Hello"))
switch(printf("World"))
while(printf("There"))
{
return 0;
}
}
Run Code Online (Sandbox Code Playgroud)
非常简单:printf("Hello")返回 5(写入的字符数)。5 不是 0,因此就 if 而言,它被认为是“真”,因此 thenprintf("World")也返回 5,开关查找 a case 5:,没有找到,然后停在那里。
首先,让我们考虑一下函数printf返回的内容。来自 C 标准
3 该
printf函数返回传输的字符数,如果发生输出或编码错误,则返回负值。
所以这个if语句的条件
if(printf("Hello"))
Run Code Online (Sandbox Code Playgroud)
评估为真,因为printf()返回一个非零值。
那么这个switch说法
switch(printf("World"))
Run Code Online (Sandbox Code Playgroud)
被评估。
现在让我们考虑该switch语句是如何工作的。来自 C 标准
4
switch语句导致控制跳转到、进入或跳过作为开关主体的语句,这取决于控制表达式的值、默认标签的存在以及开关上或开关中的任何 case 标签的值身体。case 或 default 标签只能在最接近的封闭 switch 语句中访问。
由于语句的主体语句switch没有标签(包括默认标签),因此控制通过主体语句。即不执行while语句(即语句的主体switch语句)。
如果您想获得预期的结果,例如插入标签default。
#include <stdio.h>
int main()
{
if(printf("Hello"))
switch(printf("World"))
default: while(printf("There"))
{
return 0;
}
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,程序输出是
HelloWorldThere
Run Code Online (Sandbox Code Playgroud)
或者使用空语句作为 switch 语句的主体语句。
#include <stdio.h>
int main()
{
if(printf("Hello"))
switch(printf("World")); // <==
while(printf("There"))
{
return 0;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
195 次 |
| 最近记录: |