i found this problem in c/c++
when i wrote this code
int a=5,b;
b=++a +(+=a + a--);
it gave the output of b as 21
and when i wrote
int a;
int b=++a + (++a + a--);
it gave b as 18
why the answers are varying for the same compiler(turbo c++)?
also when i tried this code in gcc compiler
the output was 20...

i m really thnkful for your response..,bt can u describe ur solution a bit more..
n suppose the problem is of sequence pts,then why the result changes based on the way i declare variable b??

The result is 100% unpredictable when you invoke undefined behavior. Trying to reason why the output is one way or another is wasted effort.

its not wasting time but some standardisation should b there,its is not a very complicated expression.nd if this is producing ambiguity widout any reason then wats the credibility of c/c++ compiler program. i m not getting this problem in languages like java. definitely there must b a problem wid the code of the compiler.

i m not getting this problem in languages like java.

Languages like Java force expressions like this to work they way the designers wanted. This is easier to manage when the compiler only has to worry about running in a virtual machine rather than any possible combination of hardware on the planet. :) The reason C++ does not enforce a strict evaluation is two fold:

  1. Leaving some expressions undefined or unspecified means compilers are free to optimize more aggressively to match the capabilities of the hardware.
  2. C++ runs on a huge number of platforms, all with different hardware and different strengths. Picking a strict evaluation may work on one machine but be very inefficient on another.

The C++ standard does not discriminate, and a lot of things are left undefined, unspecified, or implementation defined to help compilers work best for the target machine.

definitely there must b a problem wid the code of the compiler.

99% of all perceived compiler bugs are not. ;)

so finally u mean to say that there is no specified rule for these types of expressions in the compiler code in order to be able to run on all sorts of hardware combinations??(meaning sequence pts..)

I would say in order to give compilers more flexibility for generating the best possible machine code, but the spirit of your statement is on target. :)

then what should be done in such situations???

then what should be done in such situations???

Simple, don't get into those situations. :) If there is no predictable result for an expression, the best course of action is to avoid that expression. In your example you can break the expression down into multiple statements to make it do what you want, and you will make the code more clear at the same time.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.