why does these two statement behaving in the same manner?
Code:(cout<<"hello"); //1stand this one throwing an error:Code:cout<<"hello"; //2nd
Code:(cout<<"hello";) //3rd
why does these two statement behaving in the same manner?
Code:(cout<<"hello"); //1stand this one throwing an error:Code:cout<<"hello"; //2nd
Code:(cout<<"hello";) //3rd
Because
(expression;)
in C++ is a syntax error.
It's nothing special about cout.
Try
(a=1;)
1 works because cout doesn't return void.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
in 1st shouldn't it throw some error since the operator << sends its right-hand-operands i.e. "hello") into the left hand operand i.e. ostream object cout & it should be asking for the left-parenthesis (the left-parenthesis being placed before cout)?
The parentheses isn't part of operator <<'s operands. Parentheses was used for grouping.
One necessary use:
Code:#include <iostream> #include <cstdlib> bool coinflip() { return std::rand() % 2 != 0; } int main() { std::cout << (coinflip() ? "hello" : "bye") << std::endl; }
Like I said, cout returns a value, so you can put it inside parenthesised expressions.
Here's another example.
Similarly for cinCode:#include <iostream> using namespace std; int main() { if ( cout << "hello world" << endl ) { } }
Code:if ( cin >> myvar ) { // do stuff with valid data } else { // oops }
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.