Increment/decrement operator Problem

I need help with this increment statement:

expected answer was 39 & 13

BUT i get 37 & 13



#include<iostream>
using namespace std;

int main()
{
int a=10,b;
b=++a + ++a + ++a;
cout<<b<<endl;
cout<<a;
return 0 ;
}





b=++a + ++a + ++a;

That is a big undefined mess. The C++ specification doesn't say what should happen. Don't do it.

No multiple ++ on the same object between sequence points.
salmanilyas wrote:
expected answer was 39 & 13

Whoever suggested that to be an "expected answer" should stay far away from teaching and even farther away from programming.

This sequence of tokens, "++a + ++a + ++a" has precisely no meaning in C++ (or in C for that matter) because it attempts to modify the same variable more than once without sequencing. Nothing is an "expected answer" except the warnings (which should be treated as errors) from modern compilers:

gcc: https://wandbox.org/permlink/9nfEpzhRecTcIldt
prog.cc:7:9: warning: operation on 'a' may be undefined [-Wsequence-point]
 b=++a + ++a + ++a;
         ^~~


clang: https://wandbox.org/permlink/1uJGdGB1KoYUu5JE
prog.cc:7:3: warning: multiple unsequenced modifications to 'a' [-Wunsequenced]
b=++a + ++a + ++a;
  ^     ~~

Last edited on
but i get the wrong answer


There IS NO RIGHT ANSWER. It's bad C++. The C++ definition says that there IS NO RIGHT ANSWER if you do that. Do you understand that?

i saw multiple tutorials on youtube all used it and they got 39

They all should not be trying to teach C++. They're all bad teachers, unless they were doing it as an example of something that you should not do.

As a strong rule of thumb, do NOT try to learn C++ from youtube videos showing people typing in code and executing it.
Last edited on
ok because i use the same equation with only ++a + ++a and the answer was as i expected
so you mean we shouldn't use any increment or decrement operator more than twice?
ok got it sir thanks
You shouldn't use it more than ONCE.
Ok

thanks for your time sir
really appreciate it.
Topic archived. No new replies allowed.