order of print in c++ [duplicate] - c++

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the correct answer for cout << c++ << c;?
I have following code -
int a= 7;
const int &b = a;
int &c = a;
if I use
cout << endl << ++c << '\t' << a << '\t' << b << '\t' << c;
it prints
"8 7 7 8"
however if I use
cout << endl << a << '\t' << b << '\t' << ++c << '\t' << a << '\t' << b << '\t' << c;
it prints
"8 8 8 8 8 8"
How exactly this happens ? Is it something related to optimization ?? If yes, how can i switch it off in ideone.com ???

Effectively the operator<< is a function call, c++ is allowed to evaluate the arguments passed to a function in any order it likes, hence the ++c inc is done first, quite legally, by your compiler - mine does something different.
Interstingly my compiler prints
8 8 8 7 7
Some compilers provide switches for order of evaluation of function params, but if you really need to use it I would question myself on the reasons for this as there is something much more wrong with the code and instead write it in a portable way.

a, b, and c are all the same object. The order in which the arguments to functions are evaluate is undefined, however. So, you whatever the compiler chooses to evaluate first is OK. It seems, in your second expression it evaluates ++c first. The way to avoid problems is not to fold the modification with the rest of the expression, i.e., to increment c either before or after the output.

Related

#define process in C++ [duplicate]

This question already has answers here:
Macro Expansion
(7 answers)
How #define works in Programming when define has value with operator?
(4 answers)
How does #define work in C++ [duplicate]
(1 answer)
Closed 1 year ago.
I am trying C++, There is a point about can not understanding about #define addition. The example code below.
#include <iostream>
using namespace std;
#define A 0
#define B A+1
#define C 3-B
int main(){
cout << A << endl;
cout << B << endl;
cout << C;
return 0;
}
The result gives A -> 0, B -> 1, C-> 4. How C equal 4 ?
#define performs simple textual substitution. When you expand B out, you get 0+1 in source code, which is not necessarily identical to "an integer with the value 1".
So, in your example code, if we substitute the values in:
int main(){
cout << 0 << endl;
cout << 0+1 << endl;
cout << 3-0+1;
return 0;
}
3 - 0 + 1 is 4.
Do the text substitution. B expands to 0+1. C expands to 3-0+1 rather than 3-1.
cout << C;
Becomes:
cout << 3-0+1;
Because of order of operations this displays 4 rather than 2.
An easy way to see this would be to try something like:
cout << C * 50;
If we operate under the faulty assumption that C is actually 4, we'd expect to see 200. But because the above is equivalent to:
cout << 3-0+1 * 50;
Then we correctly see 53.

C++ single quotes syntax

I am learning C++ and just started reading "Programming Principles and Practice" by Bjarne Stroustrup and he uses this code to illustrate a point:
#include "std_lib_facilities.h"
using namespace std;
int main() // C++ programs start by executing the function main
{
char c = 'x';
int i1 = c;
int i2 = 'x';
char c2 = i1;
cout << c << ' << i1 << ' << c2 << '\n';
return 0;
}
I am familiar in general with the difference between double and single quotes in the C++ world, but would someone kindly explain the construction and purpose of the section ' << i1 << '
Thanks
cout << c << ' << i1 << ' << c2 << '\n';
appears to be a typo in the book. I see it in Programming Principles and Practice Using C++ (Second Edition) Second printing. I do not see it listed in the errata.
According to the book, the intended output is
x 120 x
But what happens here is ' << i1 << ' attempts to compress the << i1 << to a multi-byte character and prints out an integer (most likely 540818464-> 0x203C3C20 -> ASCII values of ' ', '<', '<', ' ') because cout doesn't know wide characters. You'd need wcout for that. End result is output something like
x540818464x
and a warning or two from the compiler because while it's valid C++ code, it's almost certainly not what you want to be doing.
The line should most likely read
cout << c << ' ' << i1 << ' ' << c2 << '\n';
which will output the expected x 120 x
In other words, Linker3000, you are not crazy and not misunderstanding the example code.
Anyone know who I should contact to log errata or get a clarification on the off chance there is some top secret sneakiness going way over my head?
Before answering your question, here is a little background on what that is actually doing. Also note that there is a typo in the example, the string constant should have been double quoted:
cout << c << " << i1 << " << c2 << "\n";
In C++, operators can be overloaded so that they mean different things with different functions. In the case of cout, the << operator is overloaded as the "Insertion Operator". Think of it as taking the operand on the right, and inserting it (or sending it) into the operator on the left.
For example,
cout << "Hello World";
This takes the string "Hello World", and sends it to cout for processing.
So what beginners do not get is what something like this means:
cout << "Hello" << " World";
This is doing the same thing, but the operator precedence says to perform the injections from left to right. To make this work, the cout object returns itself as a function return value. Why is this important? Because the above statement is actually two separate operator evaluations:
(cout << "Hello") << " World";
This first injects "Hello" to cout, which outputs it, then continues to evaluate the next inject operator. Because cout returns itself, after the (cout << "Hello") is executed you have the following still to be evaluated:
cout << " World";
This expression injects " World" into the cout object, which then outputs " World", with the net effect being that you see "Hello World" just like the first time.
So in your example, what is it doing?
cout << c << " << i1 << " << c2 << "\n";
This is evaluated left to right as follows:
((((cout << c) << " << i1 << ") << c2) << "\n"); => Outputs value of c
((((cout ) << " << i1 << ") << c2) << "\n"); => Outputs string " << i1 << "
((( cout ) << c2) << "\n"); => Outputs value of c2
(( cout ) << "\n"); => Outputs newline character
( cout ); => No more output
Expression completes and returns the cout object as the expression value.
Assuming c='x' and c2='x', the final output from this expression is the following character string output on a single line:
x << i1 << x
For beginners, all those insertion operators << look a little strange. It is because you are dealing with objects. You could build the string up as a complete formatted object before injecting it into cout, and while that make the cout expression look simpler, we do not do that in C++ because it makes your code more complex and error prone. Note also, there is nothing special about the cout object. If you wanted to output to the standard error stream, you would use cerr instead. If you wanted to output to a file, your would instantiate a stream object that outputs to the desired file. That rest of the code in your example would be the same.
In C, the same thing would be done procedurally using a format string:
printf("%d << i1 << %d\n", i1, c2);
This is allowed in C++ too, because C++ is a superset of C. Many C++ programmers still use this output method, but that is because those programmers learned C first, and may not have fully embraced the object oriented nature of C++
Note that you may also have seen the << operator in the context of mathematical expressions like:
A = A << 8;
In this case, the << operator is the bitwise rotate operation. It has nothing to do with output to cout. It will rotate the bits in A to the left by eight bits.

Swap two numbers without a third in C/C++ [duplicate]

This question already has answers here:
Swapping two variable value without using third variable
(31 answers)
Closed 6 years ago.
we usually use the
a=a+b;
b=a-b;
a=a-b;
logic to solve this code, however, if we work with int, then after say 30000 the code fails, if we take long, it fails after say 1000000 or so. My objective is, not to increase the length of the code yet, do the same operation. I have already tried using a BIT wise XOR,
a = a ^ b;
b = a ^ b;
a = a ^ b;
Still it didn't help, any ideas?
To swap a variable a and a variable b: std::swap(a, b);
Example:
int a = 10;
int b = 20;
std::cout << "Before swap\n";
std::cout << "Value of a: " << a << '\n';
std::cout << "Value of b: " << b << '\n';
std::swap(a, b);
std::cout << "After swap\n";
std::cout << "Value of a: " << a << '\n';
std::cout << "Value of b: " << b << '\n';
Output using GCC 4.9.2:
Before swap
Value of a: 10
Value of b: 20
After swap
Value of a: 20
Value of b: 10
This way of doing it uses rvalues internally, so it has next to zero overhead for other use cases and won't overflow for any primitive type ever

Why does multiple calls to xalloc result in delayed output?

When I print the id of a stream in a single expression it prints it backwards. Normally this is what comes out:
std::stringstream ss;
std::cout << ss.xalloc() << '\n';
std::cout << ss.xalloc() << '\n';
std::cout << ss.xalloc();
Output is:
4
5
6
But when I do it in one expression it prints backwards, why?
std::stringstream ss;
std::cout << ss.xalloc() << '\n'
<< ss.xalloc() << '\n'
<< ss.xalloc();
Output:
6
5
4
I know the order of evaluation is unspecified but then why does the following always result in the correct order:
std::cout << 4 << 5 << 6;
Can someone explain why xalloc behaves differently? Thanks.
This isn't related to xalloc; any other function that returns a different value each time it's called would do the same thing. The order of evaluation of the arguments is unspecified; the compiler can make the three function calls in any order. Once all the arguments have been evaluated, the order of insertion is from left to right.

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.