简体   繁体   English

为什么当 i++ 定义为 for 循环中的增量时没有立即增量,而它反映在 if 语句的情况下?

[英]Why is there no immediate increment when i++ is defined as the increment in for loop whereas it's reflected in the case of an if statement?

I'm just a beginner at C++ and I came across this instance.我只是 C++ 的初学者,我遇到了这个实例。

#include <iostream>
using namespace std;
int main(){
  int c = 3;
  int d = c++;
  if (c++ == 4 && d == 3)
    cout << "1: " << c << " " << d << endl;
  if (++c == 5 && d-- == 3)
    cout << "2: " << c-- << " " << d << endl;
  cout << "3: " << c << " " << d << endl;
}

So in this case, the output would be:所以在这种情况下,输出将是:

1: 5 3
3: 6 3 

And what I understand from this is that the variables would still be updated even if they are being called for an increment in the if statement.我从中了解到的是,即使在 if 语句中调用变量来增加变量,它们仍然会更新。

Now I came across this:现在我遇到了这个:

#include <iostream>
using namespace std:
int main(){
   for (int i= 1; i <= 10; ++i){
     cout << i ;
     break
   }
}

And even though its being incremented it's only returning 1. So I thought that maybe the 2nd time it goes through the loop (after removing the break of course) it would return 3, cause then it would have passed through ++i twice, but it's still 2. I don't understand.即使它被递增,它也只返回 1。所以我认为它可能第二次通过循环(当然在删除中断之后)它会返回 3,因为它会通过 ++i 两次,但是还是2。我不明白。 So my question is why would there be an instant increment in the if statement but there is none when ++i exists in the for loop ?所以我的问题是为什么 if 语句中会有一个即时增量,但是当 ++i 存在于 for 循环中时没有?

EDIT: just fixed a typo.编辑:刚刚修复了一个错字。 I was supposed to type semicolon but put a comma instead :b我应该输入分号,但用逗号代替:b

EDIT: added a more straightforward question as some are wondering what I am asking.编辑:添加了一个更直接的问题,因为有些人想知道我在问什么。

A for statement has 4 parts, they are not in the order they are executed. for 语句有 4 部分,它们的执行顺序不同。

for ( init-statement condition; iteration_expression) statement

Is defined as equivalent to定义为等价

{
    init_statement
    while ( condition ) {
        statement
        iteration_expression ;
    }
}

Except that除了那个

  1. Names declared by the init-statement (if init-statement is a declaration) and names declared by condition (if condition is a declaration) are in the same scope (which is also the scope of statement ).init-statement 声明的名称(如果init-statement是声明)和由condition声明的名称(如果condition是声明)在同一范围内(这也是statement的范围)。
  2. continue in the statement will execute iteration_expression continue在语句中将执行迭代表达式
  3. Empty condition is equivalent to while(true)条件等价于while(true)

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

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