Solved

why  x = 3; y = x++ * x++ then x=3 and y =9 ?

Posted on 2001-08-04
29
1,015 Views
Last Modified: 2010-08-05
Look at the following code :

int x = 3;
int y = x++ * x++;

I though the result is x = 5 and y = 12, because
x++ * x++  is evaluated as

            push x value  on stack ;           now stack has ... 3

            x = x + 1;   // x= 4

            push x value  on stack again ;  now stack has  ... 3 4

            x = x + 1; // x = 5

          // mul two nubers on stack        
           y = 3 * 4 ; ---> 12

However, when I run the above code in VC++ and C++ Builder,
the result is x = 5 and y = 9. Because the VC++, C++ Builder
evaluates x++ * x++ as

         y =  x+ x;
         x++;
         x++;

Could someone points out why the result is not x = 5 and y = 12 ?



0
Comment
Question by:thienpnguyen
  • 11
  • 4
  • 3
  • +7
29 Comments
 
LVL 33

Expert Comment

by:hongjun
ID: 6351679
Simple.

x++ is different from ++x.
The ++ at the back means postfix while the other one is prefix. Simply to say, postfix is telling the computer to take the current value of x first before doing an increment.

So
int x = 3;
int y = x++ * x++;

would be equivalent to this
int x = 3;
int y = x * x;
x = x + 1;
x = x + 1;

So result in
int x = 3;
int y = 3 * 3; // 9
x = 3 + 1; // 4
x = 4 + 1; // 5

So x = 5 while y = 9.

hongjun
0
 
LVL 6

Author Comment

by:thienpnguyen
ID: 6351718
Hi hongjun,

Why compiler doesn't not
   y = evaluate(x++)  *  evaluate(x++)
and after evaluate(x++) then x = x++.

   1. evaluate x++ ( x left  of x++ * x++ )

       result_1 = evaluate x++  ==> result_1 = 3 and x = 4

   2. evaluate x++ ( x right  of x++ * x++ ) // note x = 4

       result_2 = evaluate x++  ==> result_1 =4  and x = 5

   3. y = result_1 * result_2;

I want to know what the C Ansi rule for processing this situation.


   
0
 
LVL 6

Author Comment

by:thienpnguyen
ID: 6351731
Hi hongjun,

Why compiler doesn't not
y = evaluate(x++)  *  evaluate(x++)
and after evaluate(x++) then x = x+1.

    1. evaluate x++ ( x left  of x++ * x++ )
   
       result_1 = evaluate x++  ==> result_1 = 3 and x = 4
   
    2. evaluate x++ ( x right  of x++ * x++ ) // note x = 4
   
       result_2 = evaluate x++  ==> result_1 =4  and x = 5
   
    3. y = result_1 * result_2;

 want to know what the C Ansi rule for processing this situation.
0
 
LVL 22

Expert Comment

by:nietod
ID: 6351737
>> nt y = x++ * x++;
>> would be equivalent to this
No.  there is no sequence in this expression.  So while your explnation of the prefix vs postfix part is correct, there is no telling what this expressiom might do.  

Y could be set to x*x or (x+1)*x.  (Possibly other values).

>> I want to know what the C Ansi rule
>> for processing this situation.
The rule is that there is no rule.  The effect of the postincrement must take place at the following sequence point, but it does not have to take effecit earlier, but it can.

I'll see if I can find you the description form the standard.  But suffice to say, the expression is ambigious any value you get might be right or might be wrong, so using it is a mistake.
0
 
LVL 22

Accepted Solution

by:
nietod earned 20 total points
ID: 6351747
From the C++ standard 5.4

4 Except where noted, the order of evaluation of operands of  individual
  operators  and subexpressions of individual expressions, and the order
  in which side effects take place, is unspecified.  Between the  previ-
  ous  and  next  sequence  point  a scalar object shall have its stored
  value modified at most once by the evaluation of an expression.   Fur-
  thermore,  the  prior  value  shall  be accessed only to determine the
  value to be stored.  The requirements of this paragraph shall  be  met
  for  each  allowable  ordering of the subexpressions of a full expres-
  sion; otherwise the behavior is undefined.  [Example:
          i = v[i++];      // the behavior is undefined
          i = 7, i++, i++; // `i' becomes 9

          i = ++i + 1;     // the behavior is undefined
          i = i + 1;       // the value of 'i' is incremented
   --end example]

As you can see your expression midifies the value of x twice between sequence points (the next sequence point is the ";" and the previous one is the ";" of the preceeding statement) and thus the behavior is undefined.
0
 

Expert Comment

by:Bhawin
ID: 6352929
my dear  friend
x++ is post increment operator
so when u write x++; in your statement 1st value of x is used then x is intremented
so as ur question says that
y=x++*x++;
means
y=3*3
then
x++
means x=4
then
x++
means x=5

i hope now U can understand pre-increment operator ++x and post increment operator x++ both r different.
ask again
bhavin4@rediffmail.com
0
 
LVL 22

Expert Comment

by:nietod
ID: 6352962
bhawin, I'm not surprised that you don't understand the answer to the problem.  But I'm surprised that after reading the answer you still don't understand.  Read the answer before posting a comment!


>> y=x++*x++;
>> means
>> y=3*3
>> then
>> x++
>> means x=4
>> then
>> x++
>> means x=5
Absolutely wrong!

There is no sequence point within that expression.  x is modified twice withinn that expression.   The behavior is undefined.
0
 
LVL 3

Expert Comment

by:karouri
ID: 6353806
sorry, nietod but I think someone else has to repeat it.
The behaviour of  x++ * x++; is *undefined*.
That doesn't mean that it will not work in any compiler, but that ANSI C does not specify an answer for this, and that the result cannot be relied upon in C compilers, or even in multiple versions of a C compiler.
After all, there is nothing in that expression that cannot be done in other ways, to make it a must for this to work..
0
 
LVL 3

Expert Comment

by:null_pointer
ID: 6354097
I think the main reason for this is more to do with the precedence of operator
In the expression

y = x++ * x++;

Multiplication (*) has precedence over the operator ++ and that?s the only reason for the final output.

0
 
LVL 22

Expert Comment

by:nietod
ID: 6354173
What?  Are you guys unable to read or something?

I explained the problem.  I posted a section of the C++ standard that describes the problem.  

Why do you see the need to propose alternate explanations that are simply guesses?  Guesses that conflict with the C++ standard's official discription of the problem?  The description that I posted so there could be no doubt that it was correct!

>> Multiplication (*) has precedence over
>> the operator ++
No.  It has NOTHING to do with operator precedence.  I'm not guessing that it has nothing to do with operator precedence.  I know it has nothing to do with operator precedence because the standard says

  Between the  previous  and  next  sequence  point a
  scalar object shall have its stored value modified
  at most once by the evaluation of an expression. ...
  The requirements of this paragraph shall  be  met
  ...otherwise the behavior is undefined.

This is the only correct explanation.  Yes, tThere are lots of other explanatiosn for this, but they are incorrect!

Do you even understand the fact that different compilers will look at that statement and produce code with different behavior?  Trying to describe that as operator preecedenc--which has a precisely defined behavor--is ludicrious.
0
 
LVL 30

Expert Comment

by:Axter
ID: 6354779
Hi (nietod),
An answer should not be posted as an answer, if other experts have previously posted possible answers as comments, and/or have already made contributions to the question.

There are many experts who never post answers as answer.  Instead, they post their answers as comments.
If you read the following link, you'll see why this is the preferred method for many of our valued experts, including myself.

http://www.experts-exchange.com/jsp/cmtyQuestAnswer.jsp


Hi (thienpnguyen):
Feel free to click the [Reject Answer] button near (Answer-poster's) response, even if it seems like a good answer.
Doing so will increase your chance of obtaining additional input from other experts.  Later, you can click the [Select Comment as Answer] button on any response.
0
 
LVL 9

Expert Comment

by:jasonclarke
ID: 6355064
> An answer should not be posted as an answer, if other
> experts have previously posted possible answers
> as comments

oh, come on...not again...

in this case, nietod was justified in posting an answer, what went before him was just plain wrong...nietod is completely correct in what he says (i.e. he has provided a complete answer)

perhaps you should keep your opinions on things like this to yourself...
0
 
LVL 22

Expert Comment

by:nietod
ID: 6355288
You don't understand, jason.  There are other answers to this question.  Admitidly they are all the wrong ones. But that apparently escapes Axter.

thienpnguyen, if you want the wrong answer, you should reject my answer.  Although it seems unnecessary since others are willing ot provide them even with it locked.
0
 
LVL 3

Expert Comment

by:karouri
ID: 6355477
Now it completely overwhelms me..
Nietod had an excellent complete answer, then some one must explain it, then someone must say it is right, then nietod has to justify it is an answer, not a comment..
Respects to EE and to Axter, some times the answer is so supported by evidence that it is *the* answer, as is the case here (withh ANSI C standard referenced). I feel it should be right to propose an answer, or why the EE had put an answer option at all?
That does not mean that posting answers as comments is not the preferred method to me, just there are times at which it is valid to do it the other way.
0
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 

Expert Comment

by:lathakiranch
ID: 6356474
Dear friend,

      According to the operators precedence * is having more priority than ++ so 3*3 will be executed first then x++ will be executed i.e, x=5,y=9;
0
 
LVL 22

Expert Comment

by:nietod
ID: 6356531
>> According to the operators precedence *
>> is having more priority than ++
That is wrong.  Both the prefix and the postfix ++ operators have higher priorioty than the * operator  (Or any other mathematical or bitwise operators).

But even if you were right.  Say for one instance that * does have higher precendence than ++.  How does that explain the fact that one compiler calculates 9 for the expression and one compiler calculates 12?   Please explain that!

Here is a hint.  If you want to explain it, you could read the posted answer.  The answer is correct.



And for your further reference  Here is a C++ operator procedence table.  You might want to consult it the next time you try to explain things in therms of operator precendence.

Operator Name     Associativity
:: Scope resolution None
:: Global None
[ ] Array subscript Left to right
( ) Function call Left to right
( ) Conversion None
. Member selection (object) Left to right
-> Member selection (pointer) Left to right
++ Postfix increment None
-- Postfix decrement None
new Allocate object None
delete Deallocate object None
delete[ ] Deallocate object None
++ Prefix increment None
-- Prefix decrement None
* Dereference None
& Address-of None
+ Unary plus None
- Arithmetic negation (unary) None
! Logical NOT None
~ Bitwise complement None
sizeof Size of object None
sizeof ( ) Size of type None
typeid( ) type name None
(type) Type cast (conversion) Right to left
const_cast Type cast (conversion) None
dynamic_cast Type cast (conversion) None
reinterpret_cast Type cast (conversion) None
static_cast Type cast (conversion) None
.* Apply pointer to class member (objects) Left to right
->* Dereference pointer to class member Left to right
* Multiplication Left to right
/ Division Left to right
% Remainder (modulus) Left to right
+ Addition Left to right
- Subtraction Left to right
<< Left shift Left to right
>> Right shift Left to right
< Less than Left to right
> Greater than Left to right
<= Less than or equal to Left to right
>= Greater than or equal to Left to right
== Equality Left to right
!= Inequality Left to right
& Bitwise AND Left to right
^ Bitwise exclusive OR Left to right
| Bitwise OR Left to right
&& Logical AND Left to right
|| Logical OR Left to right
e1?e2:e3 Conditional Right to left
= Assignment Right to left
*= Multiplication assignment Right to left
/= Division assignment Right to left
%= Modulus assignment Right to left
+= Addition assignment Right to left
-= Subtraction assignment Right to left
<<= Left-shift assignment Right to left
>>= Right-shift assignment Right to left
&= Bitwise AND assignment Right to left
|= Bitwise inclusive OR assignment Right to left
^= Bitwise exclusive OR assignment Right to left
,  Comma Left to right

0
 
LVL 2

Expert Comment

by:Lockias
ID: 6356696
So then what is the difference between
 y = ++x * x++;
and
 y = THAT HAS NO DEFINED MEANING AT ALL, DEAL WITH IT!

~Lockias
0
 
LVL 22

Expert Comment

by:nietod
ID: 6356775
there is a difference.  A program with the former is properly defined (unless there are problems elsewhere) yet has undefined behavior at this point.  a program with the later is ill-formed and will not compile.  

:-)
0
 
LVL 2

Expert Comment

by:Lockias
ID: 6356837
But let me elaborate...

#define THAT ++
#define HAS
#define NO x
#define DEFINED *
#define MENAING x
#define AT ++
#define ALL
#define DEAL ;
#define WITH
#define IT

#define READ 5  
#define THE 9
#define STANDARD 12

y = THAT HAS NO DEFINED MEANING AT ALL, DEAL WITH IT

Shoule y be READ, THE, or STANDARD?

~Lockias
0
 
LVL 22

Expert Comment

by:nietod
ID: 6356924
:-)
0
 
LVL 30

Expert Comment

by:Axter
ID: 6357206
jasonclarke,
>>perhaps you should keep your opinions on things like
>>this to yourself...
I do not try to oppress your opinion.  Please do not try to oppress mine.
Just as you are free to express your opinion, so am I.
0
 
LVL 22

Expert Comment

by:nietod
ID: 6357240
When you suggest that someone reject a correct answer, you are not unduely influencing others.  An unsoliceted option like this raises doubts about an answer needlessly.

Or do you think I should begin posting cooments on all questiosn that suggest that the correct answer not be rejected?  Or even comments that suggest that the a comment be accepted asn an answer so that the person posting the comment could then work witht he client to reach a solution?

Obviously not.

maybe your time would be better spent answering questions, rather than policing the actions of others.
0
 
LVL 30

Expert Comment

by:Axter
ID: 6357265
>>maybe your time would be better spent answering
>>questions, rather than policing the actions of others.
This is not the proper place for this.
If you have problems with my posting, you and your partner need to address it to the Community Support topic area.
0
 
LVL 2

Expert Comment

by:Lockias
ID: 6357301
Does anyone know what which PAQ has the most comments with least amount of useful information.  I believe I am going to paste in the lastest source code I have for LINUX to help this one along.

~Lockias
0
 
LVL 22

Expert Comment

by:nietod
ID: 6357448
>> This is not the proper place for this.
That is my opinion.  What is this a propper place for you opinions an not mine?

If you don't think I should post comment like that, I won't.  Just stoping your and if by magic mine will stop.

>> you and your partner need to address it
>> to the Community Support topic area.
I did notify CS.  My partner is my wife and I think we should leave her out of this.
0
 
LVL 2

Expert Comment

by:Lockias
ID: 6357522
>> I think Lockias is great.
>> She should have really got the points for this.

Yes, I agree.
0
 
LVL 33

Expert Comment

by:hongjun
ID: 6366988
nietod, just spot this in another topic area. Go there and points is yours.
http://www.experts-exchange.com/jsp/qShow.jsp?ta=progsoftgen&qid=20161844

hongjun
0
 
LVL 22

Expert Comment

by:nietod
ID: 6367634
thanks.  I never would have seen it.
0
 
LVL 33

Expert Comment

by:hongjun
ID: 6368675
It's ok. I myself also never really go to that topic area. Just happen to be too free and so went there.

hongjun
0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Unlike C#, C++ doesn't have native support for sealing classes (so they cannot be sub-classed). At the cost of a virtual base class pointer it is possible to implement a pseudo sealing mechanism The trick is to virtually inherit from a base class…
C++ Properties One feature missing from standard C++ that you will find in many other Object Oriented Programming languages is something called a Property (http://www.experts-exchange.com/Programming/Languages/CPP/A_3912-Object-Properties-in-C.ht…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now