if子句中没有括号的多行代码块的奇怪行为
Strange behavior of multi-line code block in the if clause without parentheses
当我编译下面的代码片段并运行它时,我希望它也能在第12行打印语句。但这不会发生吗?为什么会这样?编译器如何处理if块中的注释?
1 #include <iostream>
2 using namespace std;
3
4 int main() {
5 int a;
6 if (false)
7 cout << "This will not be printed." << endl;
8 cout << "This will be printed anyway." << endl;
9
10 if (false)
11 // comment
12 cout << "This should also be printed. But not. Why?" << endl;
13 a = 100;
14
15 cout << "a = " << a << endl;
16 }
生产:
hyper150:~ 1041$ g++ what_if.cpp
hyper150:~ 1042$ ./a.out
This will be printed anyway.
a = 100
在生成的本地语言代码中没有任何注释。
你的代码相当于:
1 #include <iostream>
2 using namespace std;
3
4 int main() {
5 int a;
6 if (false)
7 cout << "This will not be printed." << endl;
8 cout << "This will be printed anyway." << endl;
9
10 if (false)
11 cout << "This should also be printed. But not. Why?" << endl;
12 a = 100;
13
14 cout << "a = " << a << endl;
15 }
由于第10行的条件[新代码]从未满足-第11行的cout
从未出现
它不会打印,因为它前面有if(false)
,而if (false)
永远不会计算为true。
编译器忽略注释。
还有一个建议:在像这样的if
语句中,即使只有一条语句,写大括号也会更好。
if (false)
cout << "This should also be printed. But not. Why?" << endl;
最好这样写:
if (false)
{
cout << "This should also be printed. But not. Why?" << endl;
// Most likely you are going to add more statements here...
}
如果不使用括号,if
将只接受下一个表达式:
if (false)
cout << "This will not be printed." << endl;
cout << "This will be printed anyway." << endl;
if (false)
// comment
cout << "This should also be printed. But not. Why?" << endl;
a = 100;
相当于:
if (false)
{
cout << "This will not be printed." << endl;
}
cout << "This will be printed anyway." << endl;
if (false)
{
// comment
cout << "This should also be printed. But not. Why?" << endl;
}
a = 100;
注释早在实际编译之前就被删除了。
如果不使用大括号将条件结果括起来,则条件结果以下一条语句的结尾终止,这通常意味着;性格
但它不仅是;角色,因为你可以这样做(读起来真的很可怕):
if (true)
for(int i = 0; i < 5; i++)
if (i == 4)
break;
else
h = i;
在这种情况下,for循环是下一个出现的语句,它是在h=i语句之后终止的迭代语句。
每个人对括号约定都有自己的喜好——我更喜欢使用无括号if语句,前提是它下面只有一行不需要注释(如果有else语句,那么我使用括号)。
代码优化是编译的一个阶段。在此期间,您的注释代码将从实际生成二进制文件的代码中删除。所以它把它解释为
if (false)
cout << "This should also be printed. But not. Why?" << endl;
你在if条件中加了一个false。。。。你知道后果。
在C++中,行结尾不重要;if
控制以下内容陈述在第二种情况下,以下语句是输出,所以不应该打印。注释不是语句(在在实际解析之前用空白替换事实)。因此:
if ( false ) std::cout << "no" << std::endl;
if ( false )
std::cout << "no" << std::endl;
if ( false )
std::cout << "no" << std::endl;
将不输出任何内容。
相关文章:
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 代码在main()中运行,但在函数中出现错误
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- 编译包含字符串的代码时遇到问题
- 我在c++代码中生成了一个运行时#3异常
- 如何在linux终端中同时编译和运行c++代码
- 为cl.exe(Visual Studio代码)指定命令行C++版本
- 在Linux for Windows上编译C++代码时出错
- 我的字符计数代码计算错误.为什么
- 孤立代码块在结构中引发异常
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 如何理解C++标准N3337中的expr.const.cast子句8
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 此代码是否违反一个定义规则
- 为什么我的代码在输出中增加了93天
- 我的简单if-else语句是如何无法访问的代码
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- 尝试将另一个子句添加到代码中时出错
- if子句中没有括号的多行代码块的奇怪行为