Link to home
Start Free TrialLog in
Avatar of thienpnguyen
thienpnguyen

asked on

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

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 ?



Avatar of hongjun
hongjun
Flag of Singapore image

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
Avatar of thienpnguyen
thienpnguyen

ASKER

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.


   
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.
>> 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.
ASKER CERTIFIED SOLUTION
Avatar of nietod
nietod

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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
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.
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..
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.

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.
Avatar of Axter
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.

https://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.
> 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...
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.
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.
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;
>> 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

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

~Lockias
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.  

:-)
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
:-)
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.
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.
>>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.
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
>> 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.
>> I think Lockias is great.
>> She should have really got the points for this.

Yes, I agree.
nietod, just spot this in another topic area. Go there and points is yours.
https://www.experts-exchange.com/jsp/qShow.jsp?ta=progsoftgen&qid=20161844

hongjun
thanks.  I never would have seen it.
It's ok. I myself also never really go to that topic area. Just happen to be too free and so went there.

hongjun