Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does std::cout convert volatile pointers to bool?

If you try to cout a pointer to a volatile type, even a volatile char pointer where you would normally expect cout to print the string, you will instead simply get '1' (assuming the pointer is not null I think). I assume output stream operator<< is template specialized for volatile pointers, but my question is, why? What use case motivates this behavior?

Example code:

#include <iostream>
#include <cstring>

int main()
{
    char x[500];
    std::strcpy(x, "Hello world");

    int y;
    int *z = &y;

    std::cout << x << std::endl;
    std::cout << (char volatile*)x << std::endl;

    std::cout << z << std::endl;
    std::cout << (int volatile*)z << std::endl;

    return 0;
}

Output:

Hello world
1
0x8046b6c
1
like image 322
Joseph Garvin Avatar asked Mar 23 '10 16:03

Joseph Garvin


People also ask

What is volatile bool C++?

That is, as far as I understand, when you use the Visual C++ compiler, a volatile bool is for most practical purposes an atomic<bool> . It should be noted that newer VS versions add a /volatile switch that controls this behavior, so this only holds if /volatile:ms is active.

Can bool be volatile?

In other words, you cannot declare a "pointer to volatile." Simple types such as sbyte , byte , short , ushort , int , uint , char , float , and bool .

Can we use volatile in a pointer?

Yes, you can of course have a volatile pointer.

Can we have volatile pointer in C?

Volatile is used in C programming when we need to go and read the value stored by the pointer at the address pointed by the pointer. If you need to change anything in your code that is out of compiler reach you can use this volatile keyword before the variable for which you want to change the value.


1 Answers

ostream::operator<< has the following overloads, among others:

ostream& operator<< (bool val );
ostream& operator<< (const void* val );

When you pass in a volatile pointer, the second overload can't apply because volatile pointers cannot be converted to non-volatile without an explicit cast. However, any pointer can be converted to bool, so the first overload is chosen, and the result you see is 1 or 0.

So the real reason for this is not an intentional decision on behalf of the standards committe, but simply that the standard does not specify an overload that takes a volatile pointer.

like image 152
interjay Avatar answered Oct 21 '22 12:10

interjay