在C ++中,当在控件结构中使用时,会导致赋值为true或false? [英] In C++ what causes an assignment to evaluate as true or false when used in a control structure?

查看:110
本文介绍了在C ++中,当在控件结构中使用时,会导致赋值为true或false?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,有人可以帮助我掌握一个像if(...)或while(...)等内容的所有(或大多数相关的)情况。



我的意思是:

  if(a = b)

  while =& c)
{
}

p>

何时会计算为true,什么时候计算为false?这是否改变取决于在作业中使用的类型?

解决方案

在C ++中,属性将赋值为归属值:

  int c = 5; //评估为5,你可以看到它是否打印出来
float pi = CalculatePi(); //计算结果
//调用CalculatePi函数

you statements:

  if(a = b){} 
while(a =& c){}

大致相当于:

  a = b 
if(b){}
a =& c
while(& c){}
  a = 

 $ 

 

< b
if(a){}
a =& c
while(a){}

那些 if(a)当他们不是布尔值时呢?好吧,如果他们是整数,0是假,其余的是真的。这个(一个零值 - > false,其余 - > true)通常保持,,你应该真的参考一个C ++引用确定(但请注意写如果(a == 0) if(!a)难得多,对读者来说要简单得多。 >

无论如何,您应该总是避免影响代码的副作用



从不需要执行 if(a = b):您可以通过其他方式实现完全相同的事情,更清楚,看起来像一个错误(如果我读一个代码像 if(a = b)我想到的第一件事是,开发人员写错了;第二,如果我三次检查是否正确,是我恨他!: - )



祝你好运


So can someone help me grasp all the (or most of the relevant) situations of an assignment inside something like an if(...) or while(...), etc?

What I mean is like:

if(a = b)

or

while(a = &c)
{
}

etc...

When will it evaluate as true, and when will it evaluate as false? Does this change at all depending on the types used in the assignment? What about when there are pointers involved?

Thanks.

解决方案

In C++ an attribution evaluates to the value being attributed:

int c = 5; // evaluates to 5, as you can see if you print it out
float pi = CalculatePi(); // evaluates to the result
                          // of the call to the CalculatePi function

So, you statements:

if (a = b) { }
while (a = &c) { }

are roughly equivalent to:

a = b
if (b) { }
a = &c
while (&c) { }

which are the same as

a = b
if (a) { }
a = &c
while (a) { }

And what about those if (a) etc when they are not booleans? Well, if they are integers, 0 is false, the rest is true. This (one "zero" value -> false, the rest -> true) usually holds, but you should really refer to a C++ reference to be sure (however note that writting if (a == 0) is not much more difficult than if (!a), being much simpler to the reader).

Anyways, you should always avoid side-effects that obscure your code.

You should never need to do if (a = b): you can achieve exactly the same thing in other ways that are more clear and that won't look like a mistake (if I read a code like if (a = b) the first thing that comes to my mind is that the developper who wrote that made a mistake; the second, if I triple-check that it is correct, is that I hate him! :-)

Good luck

这篇关于在C ++中,当在控件结构中使用时,会导致赋值为true或false?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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