Please be easy on me and don't shoot me as I'm still newbie.
I'm totally confused and can't for life figure out why when I run this code:
int y = 9;
cout << "++y = " << ++y << "\n--y = " << --y << "\ny++ = " << y++ << "\ny-- = " << y-- << "\n";
cout << "y = " << y << "\n";
I get the following results:
y = 9
++y = 9
--y = 9
y++ = 8
y-- = 9
y = 9
instead of these results:
y = 9
++y = 10
--y = 9
y++ = 9
y-- = 10
y = 9
That I get from this code:
int y = 9;
cout << "y = " << y << "\n";
cout << "++y = " << ++y << "\n";
cout << "--y = " << --y << "\n";
cout << "y++ = " << y++ << "\n";
cout << "y-- = " << y-- << "\n";
cout << "y = " << y << "\n";
Can anyone explain -in simple words as possible- what happens in the first code so that it prints the result that way?
A simple rule is that you are not expected to increment the same location more than once in any given statement. So you should not code cout << y++ << ++y << endl; which contain two increments of y (assuming an int y; declaration).
For details, read about sequence points and undefined behavior in the C++ standard.
There are lot of related questions. Look into them for more!
When according to the rules operation * is to be counted before +, and ++ before *, it will be so.
a*b++ + c // first b++ (returns **old** b), than a*b, than ...+c
But when you have a++ * a--, nobody can tell, what of the two operands, a++ or a-- will be evaluated the first. According to ANSII standard, even if you use the same translator, the result is every time unpredictable.
cite from the C++ ANSII standard:
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
Sequence points:
at the end of the evaluation of a full expression (a full expression is an expression statement, or any other expression which is not a subexpression within any larger expression);
at the ||, &&, ?:, and comma operators;
and at a function call (after the evaluation of all the arguments, and
just before the actual call).
So, || is a sequence point, but << is not.
Mulitiline version of first code should be:
y = 9;
cout << "y-- = " << y-- << "\n";
cout << "y++ = " << y++ << "\n"
cout << "--y = " << --y << "\n"
cout << "++y = " << ++y << "\n"
cout << "y = " << y << "\n";
Related
I'm trying to create an 2D array table in C++ with a for loop and this is my code below.
//receive user input
double nSideA = sSideA;
for( double x = nSideA; x < eSideA; x = x + incrementA){
cout << "a=" << fixed << setprecision(1) << setw(4) << nSideA << " ";
nSideA += incrementA;
} // table header
cout << "\n"; //spacing
for (double y = sSideB; y < eSideB; y = y + incrementB){
for( double x = sSideA; x < eSideA; x = x + incrementA){
sSideA += incrementA;
sSideB += incrementB;
hypo = sqrt( pow(sSideA,2) + pow(sSideB,2) );
cout << "b=" << fixed << setprecision(1) << setw(4) << sSideB << " ";
cout << fixed << setprecision(3) << setw(3) << hypo << " " << endl;
}} // content
My output for the table is something like :
b= 2.0 2.828
b= 3.0 4.243
b= 4.0 5.657
b= 5.0 7.071
b= 6.0 8.485
b= 7.0 9.899
with b not looping properly. (Printed all in a column thanks to Frax in the comments with endl;)
This is supposed to be a program that performs the Pythagoras Theorem. I intend for my output to be like
However, the results go wrong on the second loop where a[1][1] ends up at a[1][0] , a[2][2] ends up at a[2][0] and so on.
How do I fix my for loop to make it print a proper table?
Thank you.
This question already has answers here:
Undefined behavior and sequence points
(5 answers)
Closed 5 years ago.
When using a single cout to print the same variable updated multiple times, I am getting a weird order of updates. Can anybody explain how such updates are done?
int value = 2;
cout << value << value++ << ++value << endl; // 434
value = 2;
cout << ++value << value++ << value << endl; // 424
value = 2;
cout << value++ << value++ << ++value << endl; // 435
value = 2;
cout << ++value << value++ << value++ << endl; // 532
The order in which expressions in a single statement are executed is undefined. Obviously unless specified via parenthesis or rules of order of execution. For example:
int a[3]{};
int i=1;
a[i] = i++; //undefined if a[1] or a[2]
Behaviour of such code is not defined and depends on compiler and platform in use. Needless to say you should not rely on a certain behaviour of this code.
I have the following code, that I wrote to test a part of a larger program :
#include <fstream>
#include <random>
#include <iostream>
using namespace std ;
int main()
{
mt19937_64 Generator(12187) ;
mt19937_64 Generator2(12187) ;
uniform_int_distribution<int> D1(1,6) ;
cout << D1(Generator) << " " ;
cout << D1(Generator) << " " << D1(Generator) << endl ;
cout << D1(Generator2) << " " << D1(Generator2) << " " << D1(Generator2) << endl ;
ofstream g1("g1.dat") ;
g1 << Generator ;
g1.close() ;
ofstream g2("g2.dat") ;
g2 << Generator2 ;
g2.close() ;
}
The two generators are seeded with the same value, and therefore I expected the second row in the output to be identical to the first one. Instead, the output is
1 1 3
1 3 1
The state of the two generators as printed in the *.dat files is the same. I was wondering if there might be some hidden multi-threading in the random number generation causing the order mismatch.
I compiled with g++ version 5.3.0, on Linux, with the flag -std=c++11.
Thanks in advance for your help.
x << y is syntactic sugar for a function call to operator<<(x, y).
You will remember that the c++ standard places no restriction on the order of evaluation of the arguments of a function call.
So the compiler is free to emit code that computes x first or y first.
From the standard: §5 note 2:
Operators can be overloaded, that is, given meaning when applied to expressions of class type (Clause
9) or enumeration type (7.2). Uses of overloaded operators are transformed into function calls as described
in 13.5. Overloaded operators obey the rules for syntax specified in Clause 5, but the requirements of
operand type, value category, and evaluation order are replaced by the rules for function call.
That's because the order of evaluation of this line
cout << D1(Generator2) << " " << D1(Generator2) << " " << D1(Generator2) << endl ;
is not what you think.
You can test it with this:
int f() {
static int i = 0;
return i++;
}
int main() {
cout << f() << " " << f() << " " << f() << endl ;
return 0;
}
Output: 2 1 0
The order is not specified by the C++ standard, so the order could be different on other compilers, please see Richard Hodges' answer.
A slight change to the program reveals what happens:
#include <fstream>
#include <random>
#include <iostream>
using namespace std ;
int main()
{
mt19937_64 Generator(12187) ;
mt19937_64 Generator2(12187) ;
uniform_int_distribution<int> D1(1,100) ;
cout << D1(Generator) << " " ;
cout << D1(Generator) << " " ;
cout << D1(Generator) << endl ;
cout << D1(Generator2) << " " << D1(Generator2) << " " << D1(Generator2) << endl ;
}
Output:
4 48 12
12 48 4
So your Generators produce equal results - but the order the arguments of your cout-line are calculated in different order.
Try it online:
http://ideone.com/rsoqDe
These lines
cout << D1(Generator) << " " ;
cout << D1(Generator) << " "
<< D1(Generator) << endl ;
cout << D1(Generator2) << " "
<< D1(Generator2) << " "
<< D1(Generator2) << endl ;
because D1() returns an int, for which ostream::operator<<() has an overload, are effectively calling (excluding endl)
cout.operator<<(D1(Generator));
cout.operator<<(D1(Generator))
.operator<<(D1(Generator));
cout.operator<<(D1(Generator2))
.operator<<(D1(Generator2))
.operator<<(D1(Generator2));
Now, the standard has this to say,
§ 5.2.2 [4]
When a function is called, each parameter shall
be initialized with its corresponding argument.
[ Note: Such initializations are indeterminately sequenced with respect to each other — end note ]
If the function is a non-static
member function, the this parameter of the function shall be
initialized with a pointer to the object of the call
So let's break down the preceding expression
cout.operator<<(a()) // #1
.operator<<(b()) // #2
.operator<<(c()); // #3
To illustrate the construction of the this pointer, these are conceptually equivalent to (omitting ostream:: for brevity):
operator<<( // #1
&operator<<( // #2
&operator<<( // #3
&cout,
a()
), // end #3
b()
), // end #2
c()
); // end #1
Now let's look at the top-level call. Which do we evaluate first, #2, or c()? Since, as emphasized in the quote, the order is indeterminate, then we don't know—and this is true recursively: even if we evaluated #2, we would still face the question of whether to evaluate its internal #3 or b().
So that hopefully explains what's going on here more clearly.
sorry for asking you a stupid question, but I just can't figure out why I keep on getting this output.
So here is my code:
#include <cstdio>
#include <iostream>
using namespace std;
unsigned n = 4242;
int getRemainderOf(int m, int n, int& quotient);
static int l = 0;
int main()
{
int quotient; // the value of which should be changed after calling the func.
for(int i=-1; i<=1; ++i)
{
for(int j=-1; j<=1; ++j)
{
if( i && j )
{
cout << "("<< i*3 << "," << j*7 << ") " <<( getRemainderOf(i*3, 7*j, quotient) ) << " " << quotient <<endl;
cout << "("<< i*7 << "," << j*3 << ") " << getRemainderOf(i*7, 3*j, quotient) << " "; cout << quotient <<endl;
}
}
}
return 0;
}
int getRemainderOf(int m, int n, int& quotient)
{
++l;
cout << l <<endl;
quotient = m / n;
cout << " quotient " << quotient <<endl;
return m % n;
}
so what I expected to see in the first line of my output was the remainder and then the quotient that I get after calling the function getRemainderOf(). But instead when I cout the value of quotient like that I see that the value of quotient is a garbage value. So the value of the variable is not changed even though I've passed it to the function by using reference.
The funny thing is that if I cout the remainder (got by calling the function) and the quotient separately I will get it right.
I see that the problem might be in calling the function as a argument of the operator << function but I don't get it why the value of the quotient isn't changed since I call the function before I output it. This operator's associativity is left-to-right so what's wrong?
So could you please tell me what is the reason of this output.
What you've just found is a classic example of one of the quirks of C++. Your program can actually be decomposed into this simple example:
int i = 10;
f(i, ++i);
The compiler has the choice of function argument evaluation from left-to-right, but this is not guaranteed. Here's some standard text:
5.2/4 Postfix Epressions [expr.post]
When a function is called, each parameter shall be initialized with its corresponding argument. [Note: Such initializations are indeterminatly sequenced with respect to each other (1.9) - end note]
Because they are indeterminatly sequenced, the compiler has the freedom of evaluating ++i before the first argument and initializing it with the corresponding function parameter, and then evaluating i and initializing it with its respective parameter next.
The reason function call argument evaluation ambiguity is applicable here is because operator<<() is a function but it's just being called with the operator syntax. For example, this is what your code looks like if we use the operator-id syntax:
std::operator<<(std::operator<<(std::operator<<(std::cout, "(").operator<<(i*3), ",").operator<<(j*7), ")").operator<<(getRemainderOf(i*3, 7*j, quotient)).operator<<(quotient);
These are just chains of function calls with arguments and they obey the same rule as the one above.
The solution is to sequence the act of modifying the object and using it in the operator<<() call. You already achieved this with partitioning the operator<<() call into two statements with the semicolon ;, so the function is guaranteed to be called before quotient is printed.
The order of evaluation of function arguments is unspecified.
In these statements
cout << "("<< i*3 << "," << j*7 << ") " <<( getRemainderOf(i*3, 7*j, quotient) ) << " " << quotient <<endl;
cout << "("<< i*7 << "," << j*3 << ") " << getRemainderOf(i*7, 3*j, quotient) << " "; cout << quotient <<endl;
there are called overloaded operators << that are in fact functions. You have to split each statement in two statements. For example
cout << "("<< i*3 << "," << j*7 << ") " <<( getRemainderOf(i*3, 7*j, quotient) ) ;
cout << " " << quotient <<endl;
This question already has answers here:
Two different values at the same memory address
(7 answers)
Closed 5 years ago.
New to C++ and learning the const_cast — get really confused by the code below:
int main(){
const int j = 1;
int * p = (int *)(&j);
cout << j << ' ' << *p << endl;
cout << &j << ' ' << p << endl;
*p = 2;
cout << j << ' ' << *p << endl;
cout << &j << ' ' << p << endl;
const int k = 1;
int * q = const_cast<int*>(&k);
cout << k << ' ' << *q << endl;
cout << &k << ' ' << q << endl;
*q = 2;
cout << k << ' ' << *q << endl;
cout << &k << ' ' << q << endl;
return 0;
}
The outputs are
1 1
00A2FD9C 00A2FD9C
1 2
00A2FD9C 00A2FD9C
1 1
00A2FD84 00A2FD84
1 2
00A2FD84 00A2FD84
Could anyone tell me why the addresses (&i and p, or &j and q) are the same, but there values (i and *p, or j and *q) are different? I am using Visual Studio 2013RC.
That happens because the compiler can assume a const variable won't change, and hence when your code refers to it, the compiler assumes that using the variable value, or the original value at initialization won't matter, it shoudn't change behavior, so it compiles to what is faster to execute, just using constant 1 without referring to memory locations.
Using const_cast<T*>(obj) to cast away constness and modifying the object is undefined behavior if obj started its life as a constant. In your example you tell the compiler that j isn't going to change and the compiler just replaces all uses of j to become uses of 1, instead. You then break the promise and the code the compiler generated won't pay any attention to you anymore and, instead, does what it pleases.