Postfix in C++ not behaving like I'd expect [duplicate] - c++

This question already has answers here:
Why are these constructs using pre and post-increment undefined behavior?
(14 answers)
Closed 3 years ago.
I understand the basic differences between prefix/postfix notation for decrement/increment operators in C++. However, there is something going on in the next example that stumps me.
The code I shared below prints the following.
5*4**3***4****2*****1
But I would have guessed it would print this.
5*4**4***3****2*****1
How is this happening? Is something going on with pushing/popping to/from the stack?
int var = 5;
cout << var-- << '*'; //prints 5 and then decrements to 4.
cout << var << "**"; //The value of var (now 4)
//is printed to the console.
//The next line prints 3***4****.
//I would have guessed it prints 4***3****.
cout << var-- << "***" << var-- << "****";
//No matter what the above line prints,
//the value of var after the above lines is 2, so...
cout << var-- << "*****" << var << endl; //...Print 2, decrement to 1
//and then 1 is finally printed.

Welcome to the strange world of undefined behaviour. Calling an increment or decrement operator twice on the same variable, in the same statement, is undefined behaviour, so don't do it :)
#include <iostream>
int main()
{
int i = 1;
// should this print 9, 10, or 12? Compilers will vary...
std::cout << (++i + ++i + ++i) << std::endl;
return 0;
}

The problem in this line:
cout << var-- << "***" << var-- << "****";
is undefined behaviour because you using post-decrement twice in a single statement.

Related

Postfix and prefix increment [duplicate]

This question already has answers here:
Why are these constructs using pre and post-increment undefined behavior?
(14 answers)
Undefined behavior and sequence points
(5 answers)
Closed 9 years ago.
Why the output of next code is 2 1 2?
#include "iostream"
int main(int argc, const char *argv[])
{
int i = 0;
std::cout << i << std::endl << i++ << std::endl << ++i << std::endl;
return 0;
}
Because first i is equal 2 but not zero, it means that the whole like of cout is evaluated first
and then printed (not part by part). If so, then first value should be 1, but not 2, because i++ should increment i after printing. Could you clarify?
EDIT:
The output of next code is 2 2 0.
#include "iostream"
int main(int argc, const char *argv[])
{
int i = 0;
std::cout << i << std::endl << ++i << std::endl << i++ << std::endl;
return 0;
}
why?
There is no sense reasoning in the output of your code because as it stands your program exhibits Undefined Behavior.
Per paragraph 1.9/15 of the C++11 Standard:
The value computations of the operands of an operator are sequenced before the value computation of the result of the operator. If a side effect on a scalar object is unsequenced relative to either another side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined.
Because there is no sequence point separating both mutations of i, Undefined Behavior ensues. Your compiler might not output anything, and the program might output differently on different compilers. But arguing about the output is unnecessary in this context.
If you separate the statements, the result will then come out as expected:
std::cout << i << std::endl; // 0
std::cout << i++ << std::endl; // 0
std::cout << ++i << std::endl; // 2
the evalution goes from right to left.
i = 0
++i -> i = 1
i++ -> i = 1, post incrementation, a copy occurs. then i = 2
i -> i = 2
As all this occurs before being send to cout, the value of i is 2, and the middle one have been copied and its value is 1.
Please tell me if I don't understand your question clearly:
cout << i++;
is the equivalent of
cout << i;
i+=1;
while cout << ++i
is the equivalent of
i += 1;
cout << i;
in otherwords any time you use i++, post-increment it returns the current value then changes while ++i means increment first then return the new value. It has nothing to do with cout

c++ strange std::cout behaviour using pointers [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the correct answer for cout << c++ << c;?
I just ouputted text, when I suddenly noticed.
#include <iostream>
int main()
{
int array[] = {1,2,3,4};
int *p = array;
std::cout << *p << "___" << *(p++) << "\n";
// output is 1__1. Strange, but I used brackets! it should be at
// first incremented, not clear.
p = array;
std::cout << *p << "___" << *(++p) << "\n";
// output is 2_2 fine, why first number was affected? I didn't intend
// to increment it, but it was incremented
p=array;
std::cout << *p << "___" << *(p + 1) << "\n";
// output is 1_2 - as it was expected
p = array;
return 0;
}
Such behaviour is strange for me, why is it so?
You are causing undefined behaviour, so anything can happen and there's no point in speculating about why.
The expression
std::cout<<*p<<"___"<<*(p++)<<"\n"
Is one example: the order of evaluation of all the things between << is unspecified, so *p and *(p++) are unsequenced with respect to each other (i.e. the compiler is not required do do either one first). You are not allowed to modify a variable and then use it without the modification and usage being sequenced, and so this causes undefined behaviour.
The same thing applies to all the other places in that program where a variable is modified and used unsequenced separately in the same expression.

Postfix Operator Overloading Order [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Undefined Behavior and Sequence Points
I'm having trouble understanding the order of actions when overloading the postfix operator. Let's examine the two small examples below:
int i = 0;
std::cout << std::endl << "i: " << i;
i = ++i;
std::cout << std::endl << "i: " << i;
i = i++;
std::cout << std::endl << "i: " << i;
MyClass myObject;
std::cout << std::endl << "myObject: " << myObject.getMyValue();
myObject = ++myObject;
std::cout << std::endl << "myObject: " << myObject.getMyValue();
myObject = myObject++;
std::cout << std::endl << "myObject: " << myObject.getMyValue();
Two very different behaviors emerge. The output is as follows:
i: 0
i: 1
i: 2
myObject: 0
myObject: 1
myObject: 1
Different behavior, you see. Here's the outline of my overloaded-operator methods.
MyClass & MyClass::operator++ ()
{
++myValue;
return *this;
}
MyClass MyClass::operator++ (int postfixFlag)
{
MyClass myTemp(*this);
++myValue;
return myTemp;
}
Alright. Prefix makes sense. You increment whatever you need to, then return the same object, now modified, in case of assignment. But postfix is what's tripping me up. It's supposed to assign, then increment. Here we're self assigning. So with the built-in integer type, it makes sense. I assign i's value to itself, then i gets incremented. Fair enough. But let's say MyClass is a recreation of the int. It starts out at 0, gets prefix-incremented, and becomes 1. Then, the key line. myObject = myObject++. That's the same thing as myObject = myObject.operator++(int postfixFlag). It gets called. myTemp gets initialized with the value 1. It's incremented to 2. Then we return the temp. That works, if we're assigning to another object. But here I'm self-assigning, so after the increment to 2, myObject is set equal to the returned temp object initialized with the initial value, and we're back to 1! That makes sense. But it's a fundamentally different behavior.
How do I work around it? How does int do it? How is this method generally written? Do you have any comments about C++ behavior and design relating to this? Etc. I'm a little perplexed right now, since books and online examples always seem to use a variant on the method above.
Thanks for reading, and any input will be appreciated!
As others have said, with int the behaviour is undefined. But I thought I'd try to explain why for your MyClass it is not ever getting to 2.
The trick is that you are taking the following three steps in the postfix version:
Making a copy of this called myTemp (with myValue == 1).
Incrementing this->myValue (so myTemp.myValue == 1; this->myValue == 2).
Returning myTemp (with myValue == 1).
So you are modifying this, but the code that calls myObject++ is never going to see this again. It's only going to look at the value returned, which is a copy of the old myObject.
The code for operator++ is fine. The problem is how you are using it -- you shouldn't be writing the result of a pre-increment or post-increment back to the same variable (behaviour is undefined). Here is some code that might be more instructive:
int i = 0;
std::cout << "i: " << i << std::endl;
int j = ++i;
std::cout << "i: " << i << ", j: " << j << std::endl;
int k = i++;
std::cout << "i: " << i << ", k: " << k << std::endl;
MyClass myObject;
std::cout << "myObject: " << myObject.getMyValue() << std::endl;
MyClass myObject1 = ++myObject;
std::cout << "myObject: " << myObject.getMyValue()
<< ", myObject1: " << myObject1.getMyValue() << std::endl;
MyClass myObject2 = myObject++;
std::cout << "myObject: " << myObject.getMyValue()
<< ", myObject2: " << myObject2.getMyValue() << std::endl;
This prints:
i: 0
i: 1, j: 1
i: 2, k: 1
myObject: 0
myObject: 1, myObject1: 1
myObject: 2, myObject2: 1
I changed your code so that rather than assigning back to itself, it assigns to a fresh variable each time. Note that in both the int and the MyClass cases, the main variable (i/myObject) is incremented both times. However, in the pre-increment case, the fresh variable (j/myObject1) takes on the new value, while in the post-increment case, the fresh variable (k/myObject2) takes on the old value.
Edit: Just answering another part of the question, "How does int do it?" I assume this question means "what does the pre-increment and post-increment code look like in the int class, and how can I make mine the same?" The answer is, there is no "int class". int is a special built-in type in C++ and the compiler treats it specially. These types aren't defined with ordinary C++ code, they are hard-coded into the compiler.
Note: For anyone who wants to try this themselves, here is the code for MyClass that the question didn't include:
class MyClass
{
private:
int myValue;
public:
MyClass() : myValue(0) {}
int getMyValue() { return myValue; }
MyClass& operator++();
MyClass operator++(int postfixFlag);
};

Is this example causing an undefined behaviour? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Undefined Behavior and Sequence Points
The variable i is changed twice, but is the next example going to cause an undefined behaviour?
#include <iostream>
int main()
{
int i = 5;
std::cout << "before i=" << i << std::endl;
++ i %= 4;
std::cout << "after i=" << i << std::endl;
}
The output I get is :
before i=5
after i=2
Yes, it's undefined. There is no sequence point on assignment, % or ++ And you cannot change a variable more than once within a sequence point.
A compiler could evaluate this as:
++i;
i = i % 4;
or
i = i % 4;
++i;
(or something else)

Deleting a pointer to an automatic variable [duplicate]

This question already has an answer here:
What is the behavior of "delete" with stack objects? [duplicate]
(1 answer)
Closed 8 years ago.
Please look at this code
int i = 10; //line 1
int *p = &i; //line 2
delete p; //line 3
cout << "*p = " << *p << ", i = " << i << endl; //line 4
i = 20; //line 5
cout << "*p = " << *p << ", i = " << i << endl; //line 6
*p = 30; //line 7
cout << "*p = " << *p << ", i = " << i << endl; //line 8
What is the result of this code? Especially of line 3, 5 and 7? Do they invoke undefined behavior? What would be the output?
EDIT : I tried running it using g++, and it's compiling and running fine! I'm using MinGW on Windows 7.
What does Standard say in this context?
You can delete only a pointer if you have ever allocated it dynamically using new. In this case you have not allocated the pointer using new but simply defined and initialized it to point to a local variable of type int.
Invoking delete on a pointer not allocated dynamically using new is something called Undefined Behavior. In short, it means that anything on the earth can happen when such a code is executed and you can't complaint a bit to anyone on this planet.
delete p; is UB and so any further behavior can't be predicted or relied upon. You program might crash immediately or spend all your money or just exit from main() and pretend nothing happened.
Line 3 is definitely undefined behaviour, since you're trying to deleting memory at an address that is not on the heap.