0
Why if statement is executing in this code?
5 Answers
+ 8
When a string literal (even an empty one) is used in an evaluation e.g. an `if` conditional; the memory address of the literal is used instead.
Try to print the address and you'll see it's non zero even though it's an empty string literal.
printf( "%p\n", "" );
And as you probably know already, a non zero value is considered truthy, and thus the `if` block is chosen.
On the contrary, if you try to get the first char off the empty string literal; you'll get a zero ('\0' when being represented as a char) because the literal was empty. And therefore you'll end up entering the `else` block because a zero is considered falsy.
if( *"" ) // evaluates to false
Hope I get it right ...
+ 1
Ipang you mean if we use * then it will use value inside double quotation and writing without * will use address of given string ...* will point out value of empty string am I right ?
+ 1
- A snippet showing example of evaluation involving `cout` is still closely related to your recent question
https://www.sololearn.com/Discuss/3026360/?ref=app.
If you read the link in Jayakrishna's answer in that post you'll understand why it is so
if( !cout << true ) // recommend to use parentheses if( !( cout << true ) )
- As for the evaluation of '„0'
It's not a valid char literal because it contains more than one character. You should be getting a warning about this I suppose.
- About the use of * (indirection or dereference), I suppose a web search on pointer and pointer arithmetic might provide you a better explanation than any I could ever do : )
0
// Online C++ compiler to run C++ program online
#include <iostream>
using namespace std ;
int main() {
if(!cout<<true){
cout <<"True ";
}
else {cout <<"False";}
return 0;
}
In this code, condition in if statement is not executing why?
0
#include <iostream>
using namespace std ;
int main() {
if('„0'){
cout <<"True ";
}
else {cout <<"False";}
return 0;
}
This code is also executing True condition ..