Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is an empty string literal treated as true?

Why is the condition in this code true?

int main ( ) {     if ("")       cout << "hello"; // executes!     return 0; } 
like image 635
D Mehta Avatar asked Jul 02 '14 12:07

D Mehta


People also ask

Does empty string evaluate to TRUE?

Yes. All false , 0 , empty strings '' and "" , NaN , undefined , and null are always evaluated as false ; everything else is true .

Why empty string is false?

Truthy or Falsy When javascript is expecting a boolean and it's given something else, it decides whether the something else is “truthy” or “falsy”. An empty string ( '' ), the number 0 , null , NaN , a boolean false , and undefined variables are all “falsy”. Everything else is “truthy”.

What does it mean for a string to be empty?

An empty string is a string instance of zero length, whereas a null string has no value at all. An empty string is represented as "" . It is a character sequence of zero characters. A null string is represented by null . It can be described as the absence of a string instance.

Is empty string valid?

An empty string is not a valid json, then it fails.


1 Answers

A condition is considered "true" if it evaluates to anything other than 0*. "" is a const char array containing a single \0 character. To evaluate this as a condition, the compiler "decays" the array to const char*. Since the const char[1] is not located at address 0, the pointer is nonzero and the condition is satisfied.


* More precisely, if it evaluates to true after being implicitly converted to bool. For simple types this amounts to the same thing as nonzero, but for class types you have to consider whether operator bool() is defined and what it does.

§ 4.12 from the C++ 11 draft spec:

4.12 Boolean conversions [conv.bool]

A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true. A prvalue of type std::nullptr_t can be converted to a prvalue of type bool; the resulting value is false.

like image 176
dlf Avatar answered Oct 08 '22 10:10

dlf