Difference between 'cout<<cout' and 'cout<<&cout' in c++? - c++

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.

Related

If you have two consecutive cout statements, and end the first with << and no semi-colon, it still compiles on Mac. Why? [duplicate]

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

Why can't we static cast a char pointer to an int pointer?

So i was reading the learncpp tutorial, and i was trying to print the address of a char pointer, because when you do :
char c{'i'};
cout << &c << endl;
It will just print the string "i", because i guess the compiler identify a char pointer to a char array, which is a string (however i don't understand why it's just printing "i", because there is not '\0' after the character 'i').
Anyway, i then tried to static_cast the char pointer into an int pointer so that is will print the address :
char c{'i'};
cout << static_cast<int*>(&c) << endl;
But this doesn't even compile, i have an error "invalid static_cast from the type << char* >> to the type << int* >>".
Finally, i simply tried a C-type cast like this :
char c{'i'};
cout << (int*)(&c) << endl;
And it works, it prints an address.
So my questions are :
why the static_cast doesn't work ? Is there any way to make a valid "C++ style cast" from char* to int* ?
in the first example, when I "cout << &c", why does it only print "i", while i haven't put any '\0' after the character 'i' ?
Thanks
Firstly, the static_cast<int*>(&c) will fail because static_cast only allows a very specific subset of type conversions. For instance, you can static_cast between numeric types, or between two class types which are related by inheritance (i.e. one inherits the other at some point in the inheritance hierarchy).
What you're doing is simply trying to "reinterpret" the address as an address to a different type. The reason being that C++ std::ostream overloads operator<< for const char*. If you only want to print the address itself, standard convention is to convert to void* via static_cast<void*>(&c) or just (void*)&c if you're ok with C-style casts. void* is basically a pointer with no type information, which makes it perfect if all you want to do is print out the value of the address itself.
The reason the C-style case compiles is because a C-style cast employs very ... shall we say risky ... methods to perform the conversion. It's allowed to perform const_cast, reinterpret_cast, and static_cast - whatever is necessary - in order to perform the cast you specified. This behavior is detailed on cppreference.com.
As for why the example of printing the char* directly only prints a single character despite not being terminated: undefined behavior is undefined. Apparently, it just so happens that (with this compiler) the executable happens to have a zero (null) byte immediately following it, wherever it may be. The compiler might even realize you assign a value but never modify it, so it might not even be in the stack (it might be in the data segment of the executable). The moral of the story is just not to invoke undefined behavior.
Let me give an example. Printing address is same as printing pointer. Such as
Int* a;
cout<<a;// print the address Lets look another
Int a;
cout<<&a; // print the address, after casting into int*
Both are same.
Now take similar case for char, and look what happen
char a = 'a'
cout<<&a; // it is printing value of *a means char* a
So that's why &a prints the value of char rather than address, because printing the address of char, after casting, char becomes the char* which is the data type called char pointer.

Output of void pointer function

I have unearthed an old C++ DLL, and I'd like to us it in one of my projects, in VS2015.
The problem is, it does not compile. I got in touch with a guy in the team that made the code in the first place, and he is positive that the exact same code compiled with VS2010.
I have an error in an otherwise very simple function:
Extract of header:
/*
Data input
*/
istream* input; //Source of data
long inputpos; // Current position in the data stream
And the code itself:
// Helper function to increment a counter while reading a character
void* Calculator::inputstream_get(char& ch)
{
++inputpos;
return input->get(ch);
}
In the end, I get an Error C2440:
'return': cannot convert from 'std::basic_istream<char,std::char_traits<char>>' to 'void *'
It is my understanding (I'm not a C++ expert I have to say...) that void pointers could represent any type of data, am I mistaken?
Is there any way to 'cast' my istream to an void pointer?
Thanks a lot for your help
The reason why this compiles in VS 2010 (C++03) and not in VS 2015 (C++11) is that in C++03, standard library streams defined an implicit conversion to void*; the purpose of that conversion was to allow testing them for truthiness (such as while (cin >> x)) without allowing an implicit conversion to bool (which would allows such monstrosities as 1 + (cin >> x) to compile).
Note that the value of the returned void* was underspecified: it was either a null pointer when the stream is in a failed state, or an unspecified non-null pointer when the stram's in good state.
C++11 introduced the notion of explicit conversion operators and contextual conversion to bool, which means that these "hacky" conversions to void* were replaced in the standard by a safe explicit operator bool () const. Of course, this makes the code fail to compile as C++11.
How you can solve this is change Calculator::inputstream_get as follows:
void* Calculator::inputstream_get(char& ch)
{
++inputpos;
return input->get(ch) ? this : nullptr;
}
This preserves the semantics of returning a null pointer on failure, and an unspecified non-null pointer on success.
To answer your last question. You cannot cast a non pointer to a pointer. But you can cast any pointer to a void pointer with (void*)
This is the deal. http://en.cppreference.com/w/cpp/io/basic_ios/operator_bool
In C++03 that was operator void* and in C++11 that is operator bool.
Change that void* to bool. Note that after the change the code will be not usable in C++03 compiler. You can solve it in a portable fashion with
if (input->get(ch)) return true;
else return false;
Actually, the most proper way is to return reference to the actual istream object.

stream output and implicit void* cast operator function invocation

a code like
cin>> grade;
where grade is a standard data type returns a reference to cin(istream object) which enables cascaded inputs....
but i read that if
cin >>grade;
is used as a condition say in a while statement...the stream's void* cast operator function is called implicitly...and it converts reference to istream object into a non-null or null pointer depending upon success or failure of last input operation...and null pointer converts to false and non-null to true...my questions are:
what is the void * cast operator function and how does it work here
how is non-null pointer converted to true and null to false
1.what is the void * cast operator function and how does it work here
It looks something like this:
operator void* () const {
return fail() ? 0 : this;
}
The question is: why isn’t an operator bool used here? The answer is: because that allows invalid conversions which may hide bugs. The above is an example of the safe bool idiom.
However, this implementation is actually obsolete. There exist better implementations of this idiom; the article explains them.
2.how is non-null pointer converted to true and null to false
This is just how C++ works: any non-null pointer is considered equivalent to true in a conditional. Now, why does C++ invoke the operator void* here in the first place?
Essentially, when C++ sees an object of an unexpected type, it tries to apply one implicit conversion that would make the object type valid in this context. The compiler therefore tries out all available implicit conversions and looks whether the resulting type would be acceptable in this context.
This is happening her: the compiler sees while (cin >> grade). It knows that basic_istream isn’t valid in the context of a while conditional. So it finds that there is an operator void*, and a void* is valid in this context so C++ applies this conversion.

why is the address of a c++ function always True?

well why would,
#include <iostream>
using namespace std;
int afunction () {return 0;};
int anotherfunction () {return 0;};
int main ()
{
cout << &afunction << endl;
}
give this,
1
why is every functions address true?
and how then can a function pointer work if all functions share (so it seems) the same addresss?
The function address isn't "true". There is no overload for an ostream that accepts an arbitrary function pointer. But there is one for a boolean, and function pointers are implicitly convertable to bool. So the compiler converts afunction from whatever its value actually is to true or false. Since you can't have a function at address 0, the value printed is always true, which cout displays as 1.
This illustrates why implicit conversions are usually frowned upon. If the conversion to bool were explicit, you would have had a compile error instead of silently doing the wrong thing.
The function pointer type is not supported by std::ostream out of the box. Your pointers are converted to only possible compatible type - bool - and verything that is not zero is true thanks to backward compatibility to C.
There's no overload of operator<< for function pointers (except stream manipulators), but there is one for bool, so the function pointer is converted to that type before display.
The addresses aren't equal, but they're both non-null, and hence they both covert to true.
There is no overloaded function: operator<<(ostream&, int(*)()), so your function pointer is converted into the only type that works, bool. Then operator<<(ostream&, bool) is printing the converted value: 1.
You may be able to print the function address like so:
cout << (void*)&afunction << endl;
All addresses in C++ are non-zero, because zero is the NULL pointer and is a reserved value. Any non-zero value is considered true.
There cannot be an overload for function pointers for the iostream << operator, as there are an infinite number of possible function pointer types. So the function pointer gets a conversion applied, in this case to bool. Try:
cout << (void *) afunction << endl;
Which will give you the address in hex - for me the result was:
0x401344
Did you check anotherfunction() as well?
Anyway, C++ pointer addresses, like C pointer addresses, are usually virtual on most platforms and don't correspond directly to memory locations. Hence the value may be very small or unusual.
Also, they will always be true, as 0 is NULL, an invalid pointer, and anything that is over 0 is true