[英]Empty C++ if statement return a zero value?
当您放置空的if语句时,程序仍会为整数变量生成一个值(零),怎么会这样呢?
这是一个比较简单的程序,可以比较三个整数并打印所有或全部大于或小于10的整数。 在第42行,有一个带分号的空else语句。 如果用户输入z为6,则程序不应返回z1 = 0。
#include <iostream> // include iostream class for input and output
#include <string> // for strings operation
#include <sstream> // for stringstream operations
using namespace std; // use defintion from std namespace
int main ()
{
int x, y, z; // define three user-input integers
int x1, y1, z1; // variables to hold bool values
stringstream xyz; // variable to store whole bool value
int XYZ; // variable to condiition print
// prompt user for x, y and z input
cout << "Please enter x" << "\n";
cin >> x;
cout << "Please enter y" << "\n";
cin >> y;
cout << "Please enter z" << "\n";
cin >> z;
// generate bool values of x1, y1, z1
if ( 10/x < 1)
x1 = 1;
else
x1 = 0;
if ( 10/y < 1)
y1 = 1;
else
y1 = 0;
if ( 10/z < 1)
z1 = 1;
else
;
// read into xyz and then XYZ
xyz << x1 << y1 << z1;
xyz >> XYZ;
// generate 8 print statements
if (XYZ == 111)
;
if (XYZ == 000)
cout << "x, y, z < 10" << endl;
if (XYZ == 110)
cout << "x, y > 10 and z < 10" << endl;
if (XYZ == 101)
cout << "x, z > 10 and y < 10" << endl;
if (XYZ == 100)
cout << "y, z < 10 and x > 10" << endl;
if (XYZ == 011)
cout << "y, z > 10 and x < 10" << endl;
if (XYZ == 010)
cout << "x, z < 10 and y > 10" << endl;
if (XYZ == 001)
cout << "x, y < 10 and z > 10" << endl;
} // program main ends
我花了几个小时来研究此问题,但是大多数讨论都围绕if语句后的分号语法错误或其他一些主题。
(注意:第51行已更正,但在控制台上什么也不显示)。
有人在Mac OSX 10.8.4上遇到这个问题吗? 与默认的LLVM编译器有关吗?
谢谢。
正如评论中提到的那样-您很不幸。
在C ++中,没有声明的初始值的变量(如果从未赋值)最终将具有任何值(如果查询)。 有时此值为0,有时为0xcccccccc
,有时此值为堆栈上的最后一个值-它取决于编译器,程序的内存布局,早餐吃的东西等。
如果您没有为z1
分配值,则无法对其行为进行假设。 如果最终为0,那只是巧合。
杰里·科芬(Jerry Coffin)在对您的问题的评论中提到了这一点。 我测试了一下,这就是问题所在。 您可能已经解决了,但是您提供的字面量实际上是八进制字面量,而不是十进制,因此除非您感到幸运,否则这些语句将不成立。
在变量声明期间,默认情况下将z1初始化为0。 由于如果z = 6,则不会修改z1,因此z1将保持为0。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.