if i write

if(printf("C is Wonderful")
          {
          }

It worked.
But if i write

if(cout<<"C is wonderful")
          {
          }

Can anyone tell me whats the reason behind it ?

Recommended Answers

All 6 Replies

What do you mean? You didn't finish your thought there.

garbage in, garbage out. printf() is a function that returns an int which is the number of characters printed. cout is a c++ class that returns a reference to ostream object. printf() and cout are two entirely different things which do something similar but have different return values. Putting cout in an if statement like that is meaningless.

Your first one couldn't have worked in the first place as you are missing a ) and wouldn't compile

yea i would think it was because printf() is a function that reurns a value and therefore you have something for an argument within the if statement, whereas cout is a just a 'class' with an output operator as ancient dragon explained and therefore doesnt provide an argument

>whereas cout is a just a 'class' with an output operator as ancient
>dragon explained and therefore doesnt provide an argument
There's nothing wrong with using the result of cout's << operator in a conditional statement as you seem to think. All standard streams have a conversion to void* which can be used as the "argument" of a conditional statement. However, the result of cout's << operator is rarely surprising, and will usually only enter an error state when there's some catastrophic failure, so there's no point in testing it.

Now, operator>> with cin is different because it's entirely likely that a request for input could fail, which would place the stream in an error state and conversion to void* would give you a null pointer. In that case it makes a lot of sense to use an if statement:

if ( cin>> x ) {
  // Use x
}
else {
  // Error!
}

>Putting cout in an if statement like that is meaningless.
On the other hand, say you have a stream into a temporary device such as a thumb drive or floppy. If the media is suddenly removed before or during a write operation then the output will fail, and the test makes sense. If cout is redirected to be used in such a way then it's far from meaningless.

By the way, cout is not a class, it's an instance of a class. There's a big difference, but a lot of people seem to mix up the two.

Thanx Buddies I got ur points

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.