#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

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; .

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.