简体   繁体   English

C ++逻辑语句

[英]C++ logical statements

I am a grader for a C++ class. 我是C ++课程的一年级生。 My skills in the more advanced concepts are pretty lacking overall due to lack of practice, so I am not familiar with the ins-and-outs of the language. 由于缺乏实践,我在较高级概念上的技能非常缺乏,因此我对这种语言的来龙去脉并不熟悉。 My question is about a block of code with an unusual line in an assignment about dice rolls. 我的问题是关于掷骰子的作业中带有不寻常行的代码块。

#include <iostream>

using namespace std;

int main()
{
   int numSims = numSims % 12 == 0 || numSims > 1000;
   //Other irrelevant code follows
}

I can't find anything saying this is bad syntax. 我找不到任何说这是错误语法的信息。 I can't see why a student would want to do this when this kind of statement, as far as I know, can't execute. 据我所知,我无法理解为什么学生无法执行这种语句。 Is there a hidden secret here than I'm missing? 这里有没有我想念的秘密?

This will execute but with an uninitialized numSims value when the expression on the right is evaluated. 将执行此操作,但在评估右侧的表达式时将使用未初始化的numSims值。 At the end numSims will end up with either a 0 or a 1. 最后,numSims的结尾为0或1。

Edit 编辑

Taking into account all the discussion in the comments below, this is technically Undefined Behavior that can result in the program crashing on some hardware platforms. 考虑到以下注释中的所有讨论,从技术上讲,这是未定义的行为,可能导致程序在某些硬件平台上崩溃。 (It is also possible, but unlikely, for it to fire phasors or reverse the polarity of the neutron flow - depending on your hardware platform.) (也有可能,但不太可能,它会触发相量或反转中子流的极性-取决于您的硬件平台。)

On many systems in use today, the program will run and that undefined behavior (which results from trying to use the indeterminate value stored in the uninitialized numSims variable) will result in numSims ending up with either a 0 or 1. 在当今使用的许多系统上,该程序将运行,并且未定义的行为(由于尝试使用未初始化的numSims变量中存储的不确定值而导致)将导致numSims以0或1结尾。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM