1.11M Members

Why am I wrong?? Teacher says I'm wrong..

 
0
 

Am I wrong that the answer is 2?? Teacher refuses and says that it's 3 because the compiler spits out 3 for ans.. but if I do it manually with pen an paper or with the cout<<v2%v1++, it spits out 2 which is what I get on paper..

#include <iostream>

using namespace std;

int main()
{
    int ans = 0, v2 = 8, v1 = 5;
    ans = v2 % v1++;
    cout<<(ans);                    //This prints out 3..
    cout<<(v2 % v1++);            //This prints out 2..
    cin.get();
    return 0;
}

I tried it in java and C#.. and it spits out 2 and 3.. every time..

 
0
 

it printed 2 cause u didnot reset v1 try this

int ans = 0, v2 = 8, v1 = 5;
    ans = v2 % v1++;
    cout<<(ans);                    //This prints out 3..
	v1=5;                    //when you remove this line v1=6
    cout<<(v2 % v1++);            //This prints out 3 not 2..
    cin.get();
 
0
 

That makes sense.. but why is it 3 if the ++ operator comes before % operator?

//If I do:

cout<<v2 % v1;  //it prints 3..

//if I do:

cout<<v2 % v1++; //it still prints 3.. wth?

EDIT:

I come to the understanding that the ++ will get done the next time ans is called..
so:

int V = 5;
cout<< V++;  //prints 5..
cout<< V;    //prints 6..
cout<< ans;  //Prints 3..
cout<< ans;  //Prints 2..

since the ++ was applied for the next time it's called.. but this has to be wrong since ++ is always done before modulo.. :S

 
0
 

The postfix increment operator returns the current value after which it increments it but you still get a 5. Try the prefix operator to see the difference.

 
1
 

The post-increment operator ++ will increment the variable by 1 and return the value of the variable _before_ the increment. In other words, the operation is semantically equivalent to:

int post_increment(int& i) {
  int result = i;  //record the value of the variable _before_ incrementing it.
  i = i + 1;       //increment the variable 'i' by 1.
  return result;   //return the value recorded before the increment.
};

In light of the above, it comes to no surprise that the first result prints out 3.

You could rewrite the code, in more details, as follows:

int ans = 0;
    int v2 = 8;
    int v1 = 5;

    //ans = v2 % v1++; .. is equivalent to:
    int v1_original = v1;  
    v1 = v1 + 1;   // v1 is now equal to 6.
    ans = v2 % v1_original;  // the modulus is taken with the original value of v1.

    cout<<(ans);                    //This prints out 3..

    // cout<<(v2 % v1++); .. is equivalent to:
    v1_original = v1;   // v1_original is now equal to 6.
    v1 = v1 + 1;        // v1 is now equal to 7.
    int ans2 = v2 % v1_original;  // modulus with original value.
    cout << ans2;  // This prints out 2..  ( 8 % 6 ).

    cin.get();
    return 0;

It is important to understand the difference between the post-increment and pre-increment operators. The preincrement ++i will return the value of the variable _after_ the increment. The post-increment i++ will return the value the variable had _before_ the increment. In most situations, if you just need to increment the variable and don't care about the value the expression returns, the pre-increment is preferred. However, there are many situations in which the post-increment is a useful and short syntax (replacing roughly 3 lines of code, as seen above).

BTW, the pre- and post- increment operators in Java/C# should have the same behavior as in C/C++. I must assume you made a mistake when you tried the code in Java/C#.

Also, your last example with cout << ans; cout << ans; spitting out 3 then 2 must also be wrong somehow. I doubt that this is actually the code that produced the 3 and 2 output. The kind of mechanism that you are implying (that the modulo is actually performed at the next invocation of the variable 'ans') is impossible in this context. Such a mechanism (akin to what is called "lazy evaluations") is only possible, in C++, using complicated techniques under-the-hood (called "expression templates") and is certainly impossible in this simple example with primitive types.

 
0
 

Just think of the postfix operator (x++) this way: After everything is done and calculated on that line, then that variable is incremented just before leaving that line of code.

For the prefix operator (++x), the variable x is incremented at the same moment that the compiler looks at it.

 
0
 

Postfix increment after line excute what you ment is prefix

int ans = 0, v2 = 8, v1 = 5;
    ans = v2 % v1++;
    cout<<(ans);                    //This prints out 3..
	v1=5;                    //when you remove this line v1=6
    cout<<(v2 % ++v1);            //This prints out 2 not 3..
    cin.get();
 
0
 

But if the ++ executes before % then should the answer be 2??

V1++ would equal 6 before the modulo happens

 
0
 
int ans = 0, v2 = 8, v1 = 5;
	int ansPre=v2 + v2++ + v2++ ;//execute line then inc so res =8 + 8 +8
	cout<<ansPre<<endl;//24
	cout<<v2<<endl;//10
	v2=8;
	int ansPost=v2 + ++v2 + ++v2 ;//inc then execute line so res =10 + 10 +10
	cout<<ansPost<<endl;//30
	cout<<v2<<endl;//10
 
1
 

@mazzica

int ansPre=v2 + v2++ + v2++ ;//execute line then inc so res =8 + 8 +8

This is wrong. The postfix increment operator does not perform the increment after the line is completely executed. It performs the increment where it appears in the expression, however, the result of the expression is the original value.

I reiterate my equivalence code:

int post_increment(int& i) {
  int result = i;  //record the value of the variable _before_ incrementing it.
  i = i + 1;       //increment the variable 'i' by 1.
  return result;   //return the value recorded before the increment.
};

The expression:

int ansPre= v2 + v2++ + v2++;

is equivalent to:

int ansPre= v2 + post_increment(v2) + post_increment(v2);

Which, actually, has undefined behaviour due to the fact that there is no rule, in the standard, to prescribe the order by which the operands of an expression are evaluated. So, the possible results are (also note that the addition is right-to-left associative):

int ansPre = 8 + (8 + 9);    // (a)
int ansPre = 8 + (9 + 8);    // (b)
int ansPre = 10 + (8 + 9);   // (c)
int ansPre = 10 + (9 + 8);   // (d)

There is no telling what your compiler might produce as a result. This is the same reason why there is no way to tell what ( i == i++ ) will give, neither could you tell what ( i == ++i ) would yield. This is undefined behaviour! That's why one should be very careful with such increment / decrement operations within compound expressions.

@triumphost: You might want to somewhat ignore what I just said, it has to do with order of evaluation of operands in an expression or function call, which is something you should understand eventually, but for now, start by understanding pre- and post-increment operators.


>> But if the ++ executes before % then should the answer be 2??

The increment executes before the %, BUT the value that the expression v1++ evaluates to is the value that v1 had BEFORE it was incremented. So, the overall result is indeed supposed to be 3.

 
0
 

@mike_2000_17 i am sorry i had just tried the code i paste before in vs2010 c++ and it worked as i said please try it

Question Answered as of 2 Years Ago by mazzica1, mike_2000_17, MandrewP and 1 other
 
0
 

i found this :See this
unspecified to allow compilers to produce optimal code. It is claimed that the difference between what can be produced giving the compiler this freedom and requiring "ordinary left-to-right evaluation" can be significant

 
0
 

>>i am sorry i had just tried the code i paste before in vs2010 c++

Ha.. trying out the code can have deceiving results. When we talk of "undefined behavior" (or "unspecified" or "implementation defined"), it doesn't mean that running it will trigger the apocalypse. Of course, on a given compiler (and the options given to it) and on a given computer, you will get some behavior (even one that is predictable and repeatable). The important thing is that the behavior is not reliable if you ever consider changing compiler, its options, or platform.

The lesson is, if you are unsure of what a weird piece of code is supposed to output, trying it out on a compiler might not be the best way to figure it out. I would generally recommend searching reliable sources, like Bjarne's FAQ, Marshall Cline's FAQ, Herb Sutter's GOTW, www.cplusplus.com, the C++ Standard Document, and.. well.. me!

>> and it worked as i said please try it

No point, trying out code with undefined behavior on various compilers is a meaningless exercise.

Isn't it about time forums rewarded their contributors?

Earn rewards points for helping others. Gain kudos. Cash out. Get better answers yourself.

It's as simple as contributing editorial or replying to discussions labeled or OP Kudos

You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article