Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What does return !!myVar mean?

I’m reading an open code in C which uses glib, and I found 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.

Thank you in advance.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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 !.:)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading