默认情况下,布尔变量不是总是假吗? [英] Aren't Boolean variables always false by default?

查看:47
本文介绍了默认情况下,布尔变量不是总是假吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个类中声明了一个布尔变量 bool abc; ,并认为默认情况下它将为false.我程序中的 if 条件 if(abc)成立,因此我输出了abc的值,并看到其中包含值55.这正常吗?

I had declared a Boolean variable bool abc; in a class and thought that it would be false by default. An if condition in my program, if (abc), turned out to be true, so I output the value of abc, and saw that it contained the value 55. Is this normal?

我们是否总是必须分配'bool abc = false'以确保它为假?

Do we always have to assign 'bool abc=false' to be sure that it is false?

推荐答案

是的,您应该始终初始化变量.除非您亲密地学习了有必要且无必要明确地进行学习的时间,否则无论如何都应该一直进行.然后...嗯...为什么要养成好习惯?

Yes, you should always initialize your variables. Until you intimately learn the times when it is and isn't necessary to do so explicitly, you should do it all the time, no matter what. And by then...well...why stop a good habit?

要将布尔值初始化为false,足以默认构造它:

To initialize a bool to false it's sufficient to default construct it:

struct X
{
  bool b;
  X() : b() {}
};

这篇关于默认情况下,布尔变量不是总是假吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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