Search code examples
cunary-operatornegation

What does return !!myVar mean?


I'm reading an open code in C which uses glib, and I found something like this

gboolean function()
{
  guint myVar = 0;
  myVar = (!!globalVar1 + !!globalVar2 + !!globalVar3);
  return !!myVar;
}

I don't understand what's exactly happening with that double exclamation mark.


Solution

  • Let's at first consider this statement

    myVar = (!!globalVar1 + !!globalVar2 + !!globalVar3);
    

    Now according to the C Standard (6.5.3.3 Unary arithmetic operators)

    5 The result of the logical negation operator ! is 0 if the value of its operand compares unequal to 0, 1 if the value of its operand compares equal to 0. The result has type int. The expression !E is equivalent to (0==E)

    For example If you have a variable like this

    int x = 10;
    

    then applying the operator ! to the variable !x you will get 0. Applying the operator the second time !!x you will get 1. It is the same if to write x != 0.

    So the result of the assignment is a non-zero value if at least one of the operands, globalVar1, globalVar2, and globalVar3. is not equal to 0.

    The above statement can be rewritten the following way

    myVar = ( ( globalVar1 != 0 ) + ( globalVar2 != 0 ) + ( globalVar3 != 0 ) );
    

    The result of the assignment can be either 0 (if all operands are equal to 0), or 1 (if only one operand is not equal to 0), or 2 ( if two operands equal to 0), or 3 (if all operands are equal to 0).

    The function need to return 1 if at least one operand is not equal to 0 or 1 otherwise.

    You could just write in the return statement

    return myVar != 0;
    

    But the author of the code decided to write

    return !!myVar;
    

    It seems he likes very much the negation operator !.:)

    The purpose of this "balancing act" with the negation operator is to return exactly either 0 or 1.