Why program results are diffentent in such 2 cases?
case 1)
cout<<"using cout.put(c): "<<cout.put(c);
cout.put('!');
case 2)
cout<<"using cout.put(c): ";
cout.put(c);
cout.put('!');
in case 1) is:
using cout.put(c): 0x477864!
in case 2) is:
using cout.put(c): U!
To elaborate on what others have said: in case 1, the compiler
will try to find a << operator for the return value of
cout.put(c), and use it. cout.put(c) returns
a std::ostream&, for which there is no <<, but an
std::ostream will convert implicitly to a bool (C++11) or
a void* (earlier C++). So you call << for a void*
(judging from your output).
Also note that when cout.put(c) is called within the
expression is unspecified (except that it must be before the
<< for the void*). So you could easily end up with either:
Uusing cout.put(c): 0x477864!
or
using cout.put(c): U0x477864!
(Because the << are in fact function calls, which introduce
sequencing, I don't think any other combinations are possible.)
In general, anytime you have a sequence of <<, expect the
value of the right side to be output, regardless of any side
effects the expression might have. You call cout.put(c) for
its side effects, not its value, so you shouldn't use it in
a <<. (To output a single character in the sequence, just use
<< c.)
cout.put(c) returns a reference to the cout object. In the first case you print that object.
std::basic_ostream::put reference
Related
I am curious if std::cout has a return value, because when I do this:
cout << cout << "";
some hexa code is printed. What's the meaning of this printed value?
Because the operands of cout << cout are user-defined types, the expression is effectively a function call. The compiler must find the best operator<< that matches the operands, which in this case are both of type std::ostream.
There are many candidate operator overloads from which to choose, but I'll just describe the one that ends up getting selected, following the usual overload resolution process.
std::ostream has a conversion operator that allows conversion to void*. This is used to enable testing the state of the stream as a boolean condition (i.e., it allows if (cout) to work).
The right-hand operand expression cout is implicitly converted to void const* using this conversion operator, then the operator<< overload that takes an ostream& and a void const* is called to write this pointer value.
Note that the actual value resulting from the ostream to void* conversion is unspecified. The specification only mandates that if the stream is in a bad state, a null pointer is returned, otherwise a non-null pointer is returned.
The operator<< overloads for stream insertion do have a return value: they return the stream that was provided as an operand. This is what allows chaining of insertion operations (and for input streams, extraction operations using >>).
cout does not have a return value. cout is an object of type ostream. operator << has a return value, it returns a reference to cout.
See http://www.cplusplus.com/reference/iostream/ostream/operator%3C%3C/ for reference.
The only signature that matches is:
ostream& operator<< (ostream& ( *pf )(ostream&));
so it returns the pointer to the operator<< member.
the one in James' answer. :)
I believe that would be the address of the ostream object that "" got printed to
This question already has answers here:
Undefined behavior and sequence points
(5 answers)
Behavior of post increment in cout [duplicate]
(4 answers)
Closed 2 years ago.
I'm having trouble understanding how Post Increment (++), Pre Increment work together in an example.
x++ means add 1 to the variable
But I am confused with this example:
using namespace std;
/ run this program using the console pauser or add your own getch, system("pause") or input loop */
int main() {
int a;
a=8;
cout<<++a<<a++<<endl;
cout<<a<<endl;
return 0;
}
I assume this means in first increased by 1 and in second it will first assign and then increment Which means the result should be 9 8 and 9 But when I compile it, I get 10 8 and 10. I don't understand.
Your confusion has nothing to do with the pre- and post-increment, but with the evaluation order of the operator <<. There are plenty of threads on this, here is a good one imho: SO discussion about evaluation order
The summary is :
Before C++17, if you have an expression such as std::cout << f(a) << g(a) << std::endl;, the order of evaluation (f first or g first) is not specified.
This becomes clearer when we look at what the expression above means. For the overloaded operator<<, it effectively becomes
operator<<(operator<<(std::cout, f(a)), g(a));
so:
function (<--------- arg 1 --------->,<arg2>)
In this case, the evaluation is unsequenced, and it is not defined whether arg1 or arg2 will be evaluated first.
With C++17, the order is specified from left to right.
From [n4659] §8.2.2 : 5
If an operator function is invoked using operator notation, argument evaluation is sequenced as specified for the built-in operator.
I interpret this as follows: even if the operator is overloaded, if it is called as an operator (i.e. std::cout << f(a) << g(a) << std::endl;), it will effectively be evaluated as
std::cout.operator<<(f(a)).operator<<(g(a)).operator<<(std::endl);
However, if the call is made explicitely as
operator<<(operator<<(std::cout, f(a)), g(a));
it will be treated as a function call and the order is still not specified.
To be safe, you are better off splitting up your prints/evaluations in separate statements (i.e. separated by ;) unless you have a good reason not to (and know the details well), especially since different operators behave differently (e.g. + remains unsequenced after C++17).
I am trying to call a variable in my class using the this keyword in two ways but I am confused with the 2nd way. The correct way of dereferencing happens to be "(*this).num" however, I was wondering why "*(this).num" is not right as well. The error I get with *(this).num is
request for member 'num' in 'this', which is of pointer type çlass const'*
class::class(int n): num(n)
{
cout << "num= " << num << endl;
cout << "this->num" << this->num << endl;
cout << "(*this).num" << (*this).num << endl;
}
Because if you define
int i = 9;
int *ptr = &i;
cout<<*(ptr)<<endl;
and call *(ptr) it works. But why doesn't it work in my class?
It's simply a matter of operator precedence. The binary dot operator has a higher precedence than the unary star operator, so *(this).num (the parentheses have no effect there) is interpreted as *(this.num), and not as (*this).num. The compiler is telling you that, because this is a pointer, this.num doesn't make sense: you can't apply the dot operator directly to a pointer.
You are using two operators: the indirection/dereferincing operator * and the member access operator ..
If you have a look at the precedence of these operators, you'll see that . has higher precedence than * (that is, . will be applied before *), so thus *(this).num is basically the same as writing *(this.num).
Since this is a pointer, you can't use the . operator on it, which is also what the error message is telling you (try using -> instead).
The reason why your second example works, is that you're not using the . operator, and thus there is no precedence to be messed up.
. has higher precedence than *.
So writing *(this).num is equivalent to (*((this).num))). Or *(this.num).
Your second example is completely different from the first since there is no access to members . or ->.
If you don't know all the precedences, or even if you do, it's usually more readable to add the appropriate brackets.
One works and the other doesn't because they are not the same thing!
*(ptr) and *(this) are the same, but *(this).num and (*this).num are not the same, that's the whole point of adding the parentheses! They change how the sub-expressions are grouped, just like in mathematics.
The parentheses in (ptr) and (this) are completely redundant, you are grouping a single sub-expression, which does nothing. In (*this) it's not redundant, it ensures that you dereference the pointer, so in (*this).num it dereferences the pointer first and then the member access .num is applied to the result of that dereference.
Compare it to mathematics:
(1) is just 1, and similarly (ptr) is just ptr
-(1) is just -1, and similarly *(ptr) is just *ptr
But -(1 + 3) and -(1) + 3 are completely different, because you change the order of the operators.
Similarly, *(this.num) and (*this).num are completely different.
The short answer is syntax.
(ptr) looks like this: evaluate expr inside () first, then dereference the result which is in this case is int. It's fine, the same as *ptr.
*(this).num is eq. with *this.num which means get the num member of this. After that dereference num. It's incorrect as you can see because "this" is a pointer to the current object.
(*this).num means dereference this, then get the num member.
I want to know actual difference between cout<<cout and cout<<&cout in c++? In my compiler cout<<cout returns 0x477864 & cout<<&cout returns 0x477860 at any time.It shows it has 1 digit of difference between them.What are the significance of these?
When you do this:
cout << cout;
You are relying on the stream's implicit conversion to void*. This value is used (pre-c++11) for testing the state of the stream. It is unspecified what the value actually is, it just needs to be NULL if the stream is in a fail state, and a non NULL otherwise. Maybe it's returning the address of a member of the object, but it's not really important, and is implementation defined.
When you do this:
cout << &cout;
That is getting the actual address of cout.
Note that in C++11 and beyond, the first one, cout << cout;, will no longer compile, because the implicit conversion to void* no longer exists. Instead there is an explicit conversion to bool to serve the same purpose.
Distance operator- ()
{
feet = -feet;
inches = -inches;
return Distance(feet, inches);
}
I am trying to learn operator overloading. The above code is used to overload the '-' operator. However I am not able to understad, how the return statement works here. What exactly happens? How is the object returned here?
The above code runs fine, but the one written below this statement doesn't. What is the error in this code?
Distance operator- ()
{
Distance d;
d.feet=(-feet);
d.inches=(-inches);
return d;
}
First of all, the method should be const. It's the unary negation operator, which should return the "negative" version of its operand (the foo in -foo).
The easiest way to return the negative version of something is to make a new instance, and that's what your code does: it constructs a Distance object and returns it, using the negated values of the operand (which presumably is also a Distance instance).
The "return" statement behaves "as if" it were copying the newly-created Distance back to the caller, though the "Return Value Optimization" means no copy need actually be performed. So you can think of it as constructing a Distance directly at the call site with the two arguments (-feet, -inches).