Why write `!!x`, when `x` will do? [duplicate] - c++

This question already has answers here:
Double Negation in C++
(14 answers)
What is the usage of "!!" (negating twice)? [duplicate]
(3 answers)
Confused by use of double logical not (!!) operator [duplicate]
(5 answers)
Closed 2 years ago.
I often see experienced programmers write !!x, even though the expected expression is a Boolean (i.e., zero or not zero) and not an integer.
For example, a line from boost:
BOOST_ASSERT(!!p); // where `p` is a pointer
What's the point of !!p when just p will do?
What I understand by a Boolean parameter is an expression converted to a value of integral type, and the value is compared against zero, explicitly or implicitly (with if or its ternary operator equivalent).
Thus, anything that takes a Boolean and expects only 0 or 1 is wrongly implemented, if my understanding of Boolean is correct.
For clarification: it's obvious that ! converts to bool; the question is explicitly asking for why.

By default, BOOST_ASSERT(expr) expands to assert(expr). That C++ assert function takes a scalar argument, not bool. Thus, your statement, "the expected expression is a boolean," is not correct.
Classes in C++ can implement operator bool(); the basic_stream classes are examples of such: assert(std::cin) will not work. The !! operator forces the use of std::cin::operator bool(), and bool after !! will be evaluated to int 0 or 1. This is shorter than assert(bool(std::cin)).
If I were a boost author, I would expand BOOST_ASSERT(expr) to assert(!!(expr)) - as is done for ( BOOST_LIKELY(!!(expr)) ? ((void)0) ).

Closely related to the question
Warnings.
Some compilers issue warnings.
Overflow of the integer storing the Boolean.
I'll just quote the comment mentioning the behaviour
The compiler would treat the values the same either way if it's only used as an operand to an if or &&, but using !! may help on some compilers if if (!!(number & mask)) gets replaced with bit triggered = !!(number & mask); if (triggered); on some embedded compilers with bit types, assigning e.g. 256 to a bit type will yield zero. Without the !!, the apparently-safe transformation (copying the if condition to a variable and then branching) won't be safe.
Related
Some consider defining operator bool() to be "unsafe". And to have an idiomatical way to convert to bool, they define bool operator !().
So writing !!obj is to support such users. And it doesn't even hurt to do so!

Related

In C++. whats the difference between (*a).b and a->b? [duplicate]

This question already has answers here:
What is the difference between the dot (.) operator and -> in C++? [duplicate]
(14 answers)
Closed 3 years ago.
I am learning C++ in a advanced programming class from my work since I have only worked in Web and .NET languages so far.
In a midway test the instructor has marked all of my uses of (*a).b as wrong and deducted points for it, which could negatively affect my final score and I need a near perfect score to transision in work from web stack to application stack, so could some of you help me resolve this dispute?
If a is a pointer, there's no difference in functionality at all, and in fact one is expressed in terms of the other [expr.ref§2]:
The expression E1->E2 is converted to the equivalent form (*(E1)).E2; the remainder of [expr.ref] will address only the first option (dot).
If a is an instance of a class with overloaded operators * and ->, there could be a difference. But such a discrepancy would be surprising, and I'd consider the class to have a bug because of this.
In the end, it's all about convention and readability then. The -> operator exists as a shorthand for the */. pair, as it is shorter and has better precedence rules (no need for parentheses). Thus, one would indeed use it rather than */..

Comparing bool with 1 in C++ [duplicate]

This question already has answers here:
Can I assume (bool)true == (int)1 for any C++ compiler?
(5 answers)
Closed 7 years ago.
Is it correct to compare bool to 1?
In a legacy code I find often:
if (xyz.isCounterActive() == 1)
where sCounterActive() returns bool.
Obviously, if ( xyz.isCounterActive() ) is sufficient, but If I change this, I don't know which side-effects it may cause. Software is big, buggy but the customer insists, that it is working.
Compiler is VS2008
In this case result of xyz.isCounterActive() will be implicitly converted to int. There're many rules of implicit conversion, which can be found here, for example.
Probably signature of isCounterActive changed since it was introduced, and the one, who changed it, forgot to modify all isCounterActive calls.

How strict C/C++ compilers about operator precedence/evaluation? [duplicate]

This question already has answers here:
order of evaluation of || and && in c
(5 answers)
Closed 9 years ago.
This question is been on my mind for a while so time to let it out and see what what you guys you have to say about it.
In C/C++ the operator precedence is defined by the C specification but as with everything there may be backdoors or unknown / not well known things that the compilers may employ under the name of 'optimization' which will mess up your application in the end.
Take this simple example :
bool CheckStringPtr(const char* textData)
{
return (!textData || textData[0]==(char)0);
}
In this case I test if the pointer is null then I check the first char is zero, essentially this is a test for a zero length string. Logically the 2 operations are exchangeable but if that would happen in some cases it would crash with since it's trying to read a non-existent memory address.
So the question is : is there anything that enforces the order of how operators/functions are executed, I know the safest way is to use 2 IFs below each other but this way should be the same assuming that the evaluation order of the operators never ever change.
So are compilers forced by the C/C++ specification to not change the order of evaluation or are they sometimes allowed to change the order, like it depends on compiler parameters, optimizations especially?
First note that precedence and evaluation order are two different (largely unrelated) concepts.
So are compilers forced by the C/C++ specification to not change the order of evaluation?
The compiler must produce behaviour that is consistent with the behaviour guaranteed by the C language standard. It is free to change e.g. the order of evaluation so long as the overall observed behaviour is unchanged.
Logically the 2 operations are exchangeable but if that would happen in some cases it would crash
|| and && are defined to have short-circuit semantics; they may not be interchanged.
The C and C++ standards explicitly support short-circuit evaluation, and thus require the left-hand operand of the &&, ||, or ? operator to be evaluated before the right-hand side.
Other "sequence points" include the comma operator (not to be confused with commas separating function arguments as in f(a, b)), the end of a statement (;), and between the evaluation of a function's arguments and the call to the function.
But for the most part, order of evaluation (not to be confused with precedence) is implementation defined. So, for example, don't depend on f to be called first in an expression like f(x) + g(y).

Meaning of a comma in a number [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
C++ Comma Operator
that probably a trivial question, but I don't know the answer. And this has been troubling me this afternoon.
I was just writing a function to convert RVB to YUV. Nothing really special, but mistakenly used the comma (,) instead of a dot in my numbers.
It compiles but the result was not what I expected, for example "-3713796" instead of a 0-255 range number.
(0,615*(double) 61) - (0,51498*(double) 61) - (0,10001*(double) 61)
So what does it mean ?
If it's not a compilation error, it's probably usefull for something but what?
Ps: I was using C++ with Qt.
You've accidentally used the comma operator. It evaluates its first operand and discards the result, and then evaluates the second operand and returns its value and type.
In my experience, it's most commonly used in loop statements. For other uses, see Uses of C comma operator
It's the comma operator which evaluates each operand and returns the rightmost. In this case it evaluated 0, then 615*(double) 61 and resulted in a value of that product.

What does double not (!!) used on a non-boolean variable do? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Double Negation in C++ code.
I am working with production code where I have run across statements like this a few times:
Class.func(!!notABool);
The first couple of times I dismissed it as a programmer quirk (maybe to emphasize that it is a conditional statement rather than a number being passed into func?) but I have run across several statements that use the above and now I am wondering whether it actually makes a difference or not. In most cases notABool is a number(int, float, double... I have seen all 3) My initial guess was that it is akin to typing:
Class.func((bool)notABool);
but I am not entirely sure?
Yes, functionally it is exactly the same as doing (bool) notABool.
By definition, in C++ language the operand of ! is implicitly converted to bool type, so !!notABool is really the same as !! (bool) notABool, i.e. the same as just (bool) notABool.
In C language the !! was a popular trick to "normalize" a non-1/0 value to 1/0 form. In C++ you can just do (bool) notABool. Or you can still use !!notABool if you so desire.
For primitive types, yes, it's essentially equivalent to:
!(notABool != 0)
which in turn is equivalent to:
(bool)notABool
For non-primitive types, it will be a compiler error, unless you've overloaded operator!, in which case, it might do anything.
It's a legacy idiom from C, where it meant "normalize to 0 or 1". I don't think there's a reason to use it in C++ other than habit.
It's converting BOOL (define for int) to c++ bool. BOOL is a define that in some cases for true can contain different integer values. So for example BOOL a = (BOOL)1; and BOOL b =(BOOL)2; both pass check for true. But if you'll try to compare you'll find that a not equals b. But after conversion !!a equals !!b.
(bool)notABoo - is not akin, because you'll convert type of variable byte still'll have different values. !! converts not only type but in some cases values too.