Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C++
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
    int R,S,n;
    R=45,n=45;
    S=(R--) + (++R);
    cout<<S;
    return 0;
}


What I have tried:

what is the answer of the program, i got different answers from turbo cpp and dev cpp
Posted
Updated 28-Nov-18 1:25am
v2
Comments
Mohibur Rashid 27-Nov-18 20:09pm    
Turbo C++? Do you how old this is?

They are both right; they are both wrong! See here: Why does x = ++x + x++ give me the wrong answer?[^]
 
Share this answer
 
Quote:
i got different answers from turbo cpp and dev cpp
That is an hint you shouldn't use such a code. For details have a look here: c++ - Undefined behavior and sequence points - Stack Overflow[^].
 
Share this answer
 
Quote:
What is the answer of the program , I got different answers from turbo cpp and dev cpp

There is no correct answer to this program, or all answers are correct.
It is a gray zone.
C++
S=(R--) + (++R);

The compiler is free to rewrite this code in any way it see fit, no matter the way you read, understand, expect it. So each compiler makes its own truth.
So multiple increment/decrement operations on same variable make the code unpredictable from a compiler to another.
This is 1 of the pitfalls of C language.
 
Share this answer
 
because you have written unclear code in
C++
S=(R--) + (++R);

it are 3 statements
1. R--
2. ++R
3. sum up the results of 1. and 2.

So the compiler can decide what to do first. If you left out the braces you get two additional edge cases.

try some clearer code
C++
R--;
S = R;
++R;
S += R
That should result in the same value on all compilers.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900