我需要帮助理解括号的使用

I need help understanding the use of brackets

本文关键字:帮助 助理      更新时间:2023-10-16

为什么代码 1 在 if 语句后没有括号而代码 2 不起作用。代码是查看通知同一字符串的重复。

代码 1:

int main()
{
  string previous = " ";
  string current;
  while(cin >> current){
    if(previous == current)
      cout << "repeated word: " << current << endl;
      previous = current;
  }
}

代码 2:

int main()
{
  string previous = " ";
  string current;
  while(cin >> current){
    if(previous == current)
    {
      cout << "repeated word: " << current << endl;
      previous = current;
    }
  }
}

此代码:

if(previous == current)
  cout << "repeated word: " << current << endl;
  previous = current;

等于:

if(previous == current)
{
  cout << "repeated word: " << current << endl;
}
previous = current;

显然,这等于:

if(previous == current)
{
  cout << "repeated word: " << current << endl;
  previous = current;
}

您在第一个代码中放在previous = current;前面的制表符或空格与编译器无关。这只是风格(在你的情况下是误导性的风格(。