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 [duplicate]
Asked Answered
S

2

6

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

Solander answered 12/6, 2015 at 8:20 Comment(0)
I
6

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++;
Inedited answered 12/6, 2015 at 8:40 Comment(0)
B
0

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.

Bonzer answered 12/6, 2015 at 9:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.