Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

closed int a=2; printf("%d", ++a + a++);

+27 votes
asked Jun 18, 2019 by kj
closed Dec 27, 2021 by Admin
closed with the note: answered

38 Answers

–1 vote
answered Feb 3, 2020 by Mahesh Phutane (120 points)

answer is 6, as it follow right to left precedence.

    4   +    2  =  6

(++a + a++)

   4        3

–1 vote
answered Feb 3, 2020 by anonymous
5 wil be the answer because ++a indiactes pre increment operator which increments value before execution.

a++ is post increment operator which will increment the value after execution.
0 votes
answered Feb 3, 2020 by Deep
7

because:initially a=2; ++a=3 then next a++ =4. Thus, ++a + a++ = 3+4=7
0 votes
answered Feb 5, 2020 by kotha kushal (560 points)
7 because for the ++a the value becomes 3 and again a++ the value becomes 4

so,finally 3+4=7
–1 vote
answered Feb 5, 2020 by Rajeshkumar
a=2

++a=3

a++=2

++a + a++ = 5
–1 vote
answered Feb 14, 2020 by anonymous
6 is the right answer
+1 vote
answered Mar 25, 2020 by Alan Sampson (440 points)

Anyone who provided a value as an answer is wrong! This is "undefined behavior" because it's a sequence error. You can't update a variable more than once inside the same sequence point. To see the proof, add the following compiler switches: -Wall -Werror and recompile the program. The compiler issues the following error message:

main.c:15:27: error: operation on ‘a’ may be undefined [-Werror=sequence-point]
   int a=2; printf("%d\n", ++a + a++);
                           ^~~
cc1: all warnings being treated as errors

 

0 votes
answered Dec 24, 2021 by Daksh Singh (190 points)
The answer is 7.

Firstly, a is set to 2... then a gets incremented by 1 (a=3).

Note, that now a has become 3 and is still not 2!!!, thus it will get post incremented again by 1 which will make it 4.

Thus, the answer becomes 3+4=7.
commented Dec 26, 2021 by Peter Minarik (84,720 points)
See the comment above yours: the code is an illegal C code as the C standard does not specify in what order it needs to be executed, so it is totally compiler dependant.
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...