if子句中没有括号的多行代码块的奇怪行为

Strange behavior of multi-line code block in the if clause without parentheses

本文关键字:代码 子句 if      更新时间:2023-10-16

当我编译下面的代码片段并运行它时,我希望它也能在第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;

将不输出任何内容。