mardi 24 mars 2020

Why is there no immediate increment when i++ is defined as the increment in for loop whereas its reflected in the case of an if statement

I'm just a beginner at C++ and I came across this instance.

#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.

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 ofcourse) it would return 3, cause then it would have passed through ++i twice, but it's still 2. I don't understand.

EDIT: just fixed a typo. I was supposed to type semicolon but put a comma instead :b

Aucun commentaire:

Enregistrer un commentaire