Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is if(double) valid C++?

I just ran into this line of code:

if( lineDirection.length2() ){...}

where length2 returns a double. It kind of puzzles me that 0.0 is equivalent to 0, NULL, and/or false.

Is this part of the C++ standard or is it undefined behaviour?

like image 316
Viktor Sehr Avatar asked Sep 22 '10 07:09

Viktor Sehr


People also ask

How do you check if a value is double or not in C#?

You can use double. TryParse() it will return false if it couldn't create a double.

Is C++ double?

Double: The C++ double is also a primitive data type that is used to store floating-point values up to 15 digits. In the above example, variables of float and double types are initialized with floating-point values.

What is difference between double and float in C?

float is a 32-bit IEEE 754 single precision Floating Point Number – 1 bit for the sign, 8 bits for the exponent, and 23* for the value. float has 7 decimal digits of precision. double is a 64-bit IEEE 754 double precision Floating Point Number – 1 bit for the sign, 11 bits for the exponent, and 52* bits for the value.

How to use double data type in c++?

Double Floating Point: Double Floating Point data type is used for storing double-precision floating-point values or decimal values. The keyword used for the double floating-point data type is double. Double variables typically require 8 bytes of memory space. void: Void means without any value.


2 Answers

It is a very much Standard Behavior (Boolean Conversion)

$4.12/1 - "An rvalue of arithmetic, enumeration, pointer, or pointer to member type can be converted to an rvalue 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."

like image 58
Chubsdad Avatar answered Oct 02 '22 12:10

Chubsdad


Yes - the comparison is against zero (0.0), and returns false if the result is exactly zero, and true otherwise.

The behaviour is inherited from C, which treats the equivalent comparison the same way.

like image 40
Jonathan Leffler Avatar answered Oct 02 '22 14:10

Jonathan Leffler