我正在努力提高我的编程技能。下面程序的输出是
' 我在 else if 1 '。
我想知道背后的原因,为什么 x 值没有初始化为 2,而是显示为 1。

#include <iostream>
using namespace std;

int main()
{
   if (false)
   {
      cout << "I'm in if " << endl;
   }
   else if (int x=2 && true)
   {
      cout << "I'm in else if " << x << endl;
   }
   else
   {
      int y = x;
      cout << y << endl;
   }

   return 0;
}

最佳答案

根据运算符优先级,

if (int x=2 && true)

被解析为
if (int x = (2 && true))

所以 x = true 所以 1

关于c++ - 谁能解释为什么 x 显示值 1 而不是 2,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28742464/

10-11 23:12
查看更多