Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]

Tags:

c++

pointers

cout

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

like image 446
Don Nalaka Avatar asked Jun 12 '15 08:06

Don Nalaka


People also ask

What is the difference between i i 1 and i += 1 in a for loop?

The difference is that one modifies the data-structure itself (in-place operation) b += 1 while the other just reassigns the variable a = a + 1 .

What is N += 1 in Python?

Python does not have unary increment/decrement operator( ++/--). Instead to increament a value, use a += 1. to decrement a value, use− a -= 1.

Is it += or =+ in Python?

The Python += operator performs an addition operator and then assigns the result of the operation to a variable. The += operator is an example of a Python assignment operator.

Is += 1 the same as ++?

These two are exactly the same. It's just two different ways of writing the same thing. i++ is just a shortcut for i += 1 , which itself is a shortcut for i = i + 1 . These all do the same thing, and it's just a question of how explicit you want to be.


1 Answers

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++;
like image 92
Daniele Avatar answered Oct 14 '22 16:10

Daniele