I assume this just returns an int. Is there anything else going on I should be aware of? C/C++ differences?
float a = 2.5;
!a; // What does this return? Int? Float?
The logical NOT ( ! ) operator (logical complement, negation) takes truth to falsity and vice versa. It is typically used with boolean (logical) values. When used with non-Boolean values, it returns false if its single operand can be converted to true ; otherwise, returns true .
% operator cannot be used with floating point numbers in C & C++.
The logical NOT operator is represented as the '!' symbol, which is used to reverse the result of any given expression or condition. If the result of an expression is non-zero or true, the result will be reversed as zero or false value.
'' If there is no minus zero, then 0.0 and -0.0 are both interpreted as simply a floating-point zero.
Regarding C++, quoting C++11 §5.3.1/9:
The operand of the logical negation operator
!
is contextually converted tobool
; its value istrue
if the converted operand isfalse
andfalse
otherwise. The type of the result isbool
.
So what's really relevant here is the behavior of static_cast<bool>(some_float)
– quoting §4.12/1:
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 tofalse
; any other value is converted totrue
. A prvalue of typestd::nullptr_t
can be converted to a prvalue of typebool
; the resulting value isfalse
.
Putting those together, 2.5f
is a non-zero value and will consequently evaluate to true
, which when negated will evaluate to false
. I.e., !a
== false
.
Regarding C, quoting C99 §6.5.3.3/5:
The result of the logical negation operator
!
is0
if the value of its operand compares unequal to0
,1
if the value of its operand compares equal to0
. The result has typeint
. The expression!E
is equivalent to(0==E)
.
I.e. the net result is the same as with C++, excepting the type.
From here
A float will be converted to false if its exactly 0.0f,
It will be also true if its not exacly 0.0f!
Inifinity will also be converted to true.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With