why n*n results as 4 at the first instant of the loop ? to me it should be 1*1. instead it comes as 2*2

110 views Asked by At

Why "n*n" results as 4 at the first instant of the loop? to me it should be 1*1. instead it comes as 2*2.

Please give me a simple answer as i'm 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

2

There are 2 answers

0
Daniele On

The evaluation order of elements in an expression is unspecified, except some very particular cases, such as the && and || etc.

writing:

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

you suppose an order and in particulr that n++ is the last evaluated.

To solve this problem you could split the exression in two parts:

cout<< "i = "<< i << "n*n = "<<n*n<< "n++ = "<< n<< " *p "<<endl;
n++;
0
Andreas DM On

Order of evaluation is not specified, it's not left to right as you may think and it's not right to left.

Split the code like Daniele suggested if your code relies on order.

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