Why does n * n get like 4 at the first moment of the loop? for me it should be 1 * 1. instead it comes as 2 * 2

Why does "n * n" get like 4 at the first moment of the loop? for me it should be 1 * 1. instead, it comes as 2 * 2.

Please give me a simple answer as I am still a beginner :)

#include <iostream> using namespace std; int main(){ int n =1 , *p; p = &n; char aString[] = {"student"}; for (int i = 0; i<5; i++) cout<< "i = "<< i << "n*n = "<<n*n<< "n++ = "<< n++<< " *p "<<endl; system ("pause"); return 0; } 

http://ideone.com/nWugmm

+6
source share
2 answers

The order in which elements are evaluated in an expression is unspecified, except in some very special cases, such as && and || and etc.

recording:

 cout<< "i = "<< i << "n*n = "<<n*n<< "n++ = "<< n++<< " *p "<<endl; 

you assume the order and, in particular, that n ++ is the last evaluated.

To solve this problem, you can divide the expression into two parts:

 cout<< "i = "<< i << "n*n = "<<n*n<< "n++ = "<< n<< " *p "<<endl; n++; 
+6
source

The evaluation procedure is not specified, it is not left to the right, as you think, and it is not right to the left.

Separate the code, for example, Daniele, if your code depends on the order.

And compile your code with a high warning level, the compiler can help you determine this.

0
source

Source: https://habr.com/ru/post/988984/


All Articles