954,498 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

"volatile string" why has 1 output?

#include <iostream>

int main()
{
    for(int i; i<3; i++){
        volatile char str[]="hello\n";
        std::cout<<str<<std::endl;
    }
    return 0;
}


Why? its gives output 1
1
1

Rhohitman
Junior Poster in Training
86 posts since Dec 2007
Reputation Points: 10
Solved Threads: 5
 

Short answer: cout is interpreting the object as a bool due to the volatile qualifier. It's a quirk of overloading for the << operator.

Long answer: A volatile pointer can't be converted to a non-volatile pointer without an explicit cast, so neither the char* nor the void* overload can be used when the << operator is called. There's no volatile qualified overload, and the closest match is the bool overload, thus your array is interpreted as a boolean value rather than an address or a string.

You can fix it a number of ways, but an explicit cast is probably what you wanted:

std::cout<< (char*)str <<std::endl;

p.s. While your compiler may set uninitialized variables to 0 automatically, it's a very bad idea to rely on that behavior because it's not universal. So in your loop, int i; should be int i = 0; .

Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

Thanx for explanation Narue!
int i; was the slip! ;)

Rhohitman
Junior Poster in Training
86 posts since Dec 2007
Reputation Points: 10
Solved Threads: 5
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: