【发布时间】:2022-12-02 00:42:14
【问题描述】:
#include<stdio.h>
int main()
{
int value = 0 ;
if(value)
printf("0");
printf("1");
printf("2");
return 0;
}
The output of the above code is 12
but when I tweak the code by adding curly brackets the output differs
#include<stdio.h>
int main()
{
int value = 0 ;
if(value)
{
printf("0\n");
printf("1\n");
printf("2\n");
}
return 0;
}
After adding curly brackets I didn't get an output.
When I change the declared variable to 1 I expected the program to only output the line printf("2") because when the value = 0 it gave 12 as the output excluding the first printf statment, So I expected changing the assigned variable value = 1 as the output would exclude both the first and second printf statments, but it didn't. This made me more confused.
Summary:
If there is no curly bracket{} in the code it gives a different output for the same code with curly brackets
When I declare value=1 or any other number program prints 012(in both codes).
I would like to know why is this happening.
Thank you.
【问题讨论】:
-
ifapplies to the next statement only. If the next statement happens to be a{}- enclosed block, it will apply to that block. -
Um,
ifis notswitch. You said "I expected changing the assigned variable value = 1 as the output would exclude both the first and second printf statments". Not sure where you got that idea. -
@SteveSummit in the code int n=4; printf(n+"goodbye") the output is bye , So I thought when value =0 it exludes the first statement then when the value is increased by 1 it should exclude another statement as well....
-
@MasterShahaam Okay. If you write
printf(n+"goodbye")that's completely different, that's pointer arithmetic. I hope you know this now, but that has nothing to do withifstatements, or the way C handles true/false.
标签: c if-statement curly-braces