// Example program
#include <iostream>
#include <string>
int main()
{
int i=1;
int x;
x = ++i + ++i + ++i;
std::cout<< x;
return 0;
}
////////Why am I getting 10 and not 9 ?
/* if i starts at 1, increment operator takes precedence
so that means 2 3 4 then 2+3+4 = 9 not 10 ??
so how am I getting 10 ??
*/
CodyOebel
-2
Junior Poster in Training
Recommended Answers
Jump to PostRule 1 when experimenting with operator precedence. Do one thing at a time. You have five operations going on here. They clearly aren't happening in the order you think they are.
Change the line to this and see what happens:
x = i + ++i;
To …
Jump to PostOkay, one more post. According to this link:
http://en.cppreference.com/w/cpp/language/operator_incdec
if you go about halfway down, they have an example. Key l;ine of code is below:
// int n6 = n1 …
All 6 Replies
AssertNull
1,094
Practically a Posting Shark
AssertNull
1,094
Practically a Posting Shark
AssertNull
1,094
Practically a Posting Shark
CodyOebel
commented:
You are Brilliant :). So this is compiler dependent and all around bad programming practice.
+3
CodyOebel
-2
Junior Poster in Training
CodyOebel
-2
Junior Poster in Training
AssertNull
1,094
Practically a Posting Shark
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.