下面C代码是什么意思 [英] What is the meaning of below C code

查看:125
本文介绍了下面C代码是什么意思的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以基本上我正在寻找下面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. The if statement first checks the variable a and since that is zero the entire expression will be false. And since it is false the printf statement will not be executed.


Richard already gave you the correct solution.
I would suggest you to focus on the if 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 see b is not incremented, simply because ++b is never executed.
Because, in turn, a is 0, and there's no reason to continue evaluation (see, for better wording: Short-circuit evaluation - Wikipedia[^]).

This C feature is used, for instance, in code like

if ( p && p->is_running() )
{
  // do stuff
}


if p is NULL then p->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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆