0

I need a and b value.

a=2; 
b=a+=++a;
a+=-b;

Solution is:
a=0
b=6

Why is this the right answer? I know it's simple but I am sure I'm doing something wrong. Tried so many times to do it that I can't even think.

Mike
  • 2,166
  • 1
  • 14
  • 29
cerouno
  • 67
  • 6
  • No sane person would write "b=a+=++a;" in a proprietary/open source code, is this a homework? – jDAQ Jun 10 '20 at 05:20
  • 10
    I’m voting to close this question because it's a pure software question not related to firmware and should be asked on Stack Overflow instead (where it will get immeditately closed for being the #1 C programming FAQ of all time). – Lundin Jun 10 '20 at 06:28

1 Answers1

9

b=a+=++a; invokes undefined behavior. The code is simply wrong and buggy, since the different side effects on a aren't sequenced in relation to each other. There is no expected outcome and there is no point in reasoning about different results you might be getting.

Details can be found at the extremely common FAQ over at SO: Why are these constructs using pre and post-increment undefined behavior?

Lundin
  • 20,162
  • 1
  • 26
  • 76
  • 1
    Its is also interesting to look at https://godbolt.org/ and see what assembly code different compilers generate. – jDAQ Jun 10 '20 at 07:52
  • 3
    @jDAQ Why is it interesting to view disassembly of broken code? There's nothing to learn from it. In this case, the compiler doesn't even have to generate any machine code at all. – Lundin Jun 10 '20 at 07:54
  • 1
    I said it is 'interesting' because it allows one to quickly compile using different compilers, too bad there's nothing to learn from it. – jDAQ Jun 10 '20 at 08:38