Monday, November 13, 2006

C++ : What's the value of i++ + i++?

It's undefined !! Basically, in C and C++, if you read a variable twice in an expression where you also write it, the result is undefined. Don't do that. Another example is:

 v[i] = i++;
Related example:
 f(v[i],i++);
Here, the result is undefined because the order of evaluation of function arguments are undefined.

You can even check it from Bjarne's own blog on C++ FAQs.

3 comments:

Girish Gaitonde said...

Hello,
when i executed the following code on c++ it got executed.

#include "iostream.h"
void main()
{
int i=10;
i++ + i++;
cout i;
}

So can i know,what exactly is the problem......

Rgds
Girish

Zaman Bakshi said...

Girish, undefined behaviour doesn't mean that it is an error, but it means that you can't be sure of the result. Different compilers will give different results because the standard takes no claim of what the result will be.

A latest compiler should flash a warning.

Girish Gaitonde said...

Thanx very much for clearing my doubts.