下面C代码是什么意思 [英] What is the meaning of below C code
问题描述
所以基本上我正在寻找下面C代码输出的解释,
int a = 0,b = 1;
if(a&& ++ b)
printf(%d,b);
我是什么尝试过:
我得到的答案是1.但我的查询是if语句在这里的用法是什么。如果我们将b从1增加到2,那么为什么它打印1 ...请帮帮我
你应该自己运行代码,你会看到没有输出。if
语句首先检查变量a
,因为该值为零,整个表达式将为false。由于它是假的,printf
语句将不会执行。
Richard已经为您提供了正确的解决方案。
我建议你专注于if
语句,试试
#include < stdio.h >
int main()
{
int a = 0 ;
int b = 1 ;
if (a&& ++ b)
{
printf( 非零branch\\\
);
}
else
{
printf( 零分支,b =%d \ n,b);
}
return 0 ;
}
输出:
零分支,b = 1
你看到b
没有增加,只是因为++ b
是从未执行。
因为,反过来,a
是0
,并且没有理由继续评估(参见更好的措辞:短路评估 - 维基百科 [ ^ ])。
这个C
功能用于例如
if (p&& p-> is_running())
{
// 做东西
}
如果p
是NULL
然后p-> is_running()
不会被执行,从而防止程序崩溃。
我在下面的编译器上运行了onlne程序,
https://www.onlinegdb.com/online_c_compiler
并且输出为1.我同意你的观点,即if语句会导致错误...但是为什么输出1?您可以尝试在上面的编译器上运行
So basically i am looking for the explanation for below C code output,
int a=0,b=1;
if (a && ++b)
printf("%d",b);
What I have tried:
The answer i got is 1. But my query is what is the use of if statement here. and if we increment b to 2 from 1, then why it prints 1... Please help me out
You should run the code yourself, and you will see that there is no output. Theif
statement first checks the variablea
and since that is zero the entire expression will be false. And since it is false theprintf
statement will not be executed.
Richard already gave you the correct solution.
I would suggest you to focus on theif
statement, try
#include <stdio.h> int main() { int a = 0; int b = 1; if ( a && ++b) { printf("non-zero branch\n"); } else { printf("zero-branch, b = %d\n", b); } return 0; }
It outputs:
zero-branch, b = 1
You seeb
is not incremented, simply because++b
is never executed.
Because, in turn,a
is0
, and there's no reason to continue evaluation (see, for better wording: Short-circuit evaluation - Wikipedia[^]).
ThisC
feature is used, for instance, in code like
if ( p && p->is_running() ) { // do stuff }
ifp
isNULL
thenp->is_running()
is not excuted thus preventing a program crash.
I have run the program onlne on below compiler,
https://www.onlinegdb.com/online_c_compiler
And the output is 1. I agree to your point that the if statement will result false... But then Why the output 1 ? You can try running on above compiler
这篇关于下面C代码是什么意思的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!