Click here to Skip to main content
15,923,006 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
C++
int a=1, b=4, c=3, n;
n=(++a*b)-(c--);
a=b++*b++*b++;


What is the value of n, a, b, c after executing the above code?

What I have tried:

n=(++4)-(3--) = 5-2 = 3 — Correct?

a=4++*4++*4++ = 5*5*5 = 125 — Correct?
Posted
Updated 27-Aug-17 20:37pm
Comments
Graeme_Grant 27-Aug-17 2:50am    
Try running the code...

Run the code and see for yourself. And as a general rule such expressions will not guarantee the results you expect, so do not use them.
 
Share this answer
 
v2
Comments
Pallav Jyoti Pal 27-Aug-17 3:24am    
would you please help me so that I can understand and get the answer. I know Suffix and Prefix increments denoted by a++ and ++a respectively.
Richard MacCutchan 27-Aug-17 3:30am    
Like I said, do not use expressions like that, as the compiler will not necessarily generate the code that you expect.
read this:
C Operator Precedence - cppreference.com[^]
C++
// This line
n=(++a*b)-(c--);
// translate to
++a;
n=(a*b)-(c);
c--;


this line is in gray zone and depend on compiler, thus it is unpredictable:
C++
a=b++*b++*b++;
// can be
a=4*4*4;
// as well as
a=4*5*6;


Use the debugger to see what your code is really doing.

There is a tool that allow you to see what your code is doing, its name is debugger. It is also a great learning tool because it show you reality and you can see which expectation match reality.
When you don't understand what your code is doing or why it does what it does, the answer is debugger.
Use the debugger to see what your code is doing. Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute.

Debugger - Wikipedia, the free encyclopedia[^]

Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
Basic Debugging with Visual Studio 2010 - YouTube[^]
The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't find bugs, it just help you to. When the code don't do what is expected, you are close to a bug.
 
Share this answer
 
Just to illustrate through a real example, that the value of such expressions can be compiler dependent, try with this simple modification:
a=b++*++b*++b;

With gcc (compiler) you get value of 150 for 'a'
and with bcc32 (Borland C++ compiler) you get 216 for 'a'.

To know 'why', you will need to see the assembly language output
 
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