What does the expression "! (errS & errE)" in the if?

-2

In a part of a code that I need to understand, a new syntax appeared for me in if :

if (!(errS&errE)) {
    fprintf(stderr, "\nFALTA ARGUMENTOS\n");
    if(!errS)
        fprintf(stderr, "-s NOME ARQUIVO SAIDA \n");
    if(!errE)
        fprintf(stderr, "-e NOME ARQUIVO ENTRADA \n");
    exit(1);

errS and errE are variables, but I did not understand which condition should be satisfied. The use of ! is strange to me. I know != is different, but only ! I do not know. What does it mean?

    
asked by anonymous 04.04.2018 / 08:47

2 answers

4

Let's write the code more readable:

if (!(errS & errE)) {
    fprintf(stderr, "\nFALTA ARGUMENTOS\n");
    if (!errS) fprintf(stderr, "-s NOME ARQUIVO SAIDA \n");
    if (!errE) fprintf(stderr, "-e NOME ARQUIVO ENTRADA \n");
    exit(1);
}

Although in this case it works I consider the first expression evaluated an error.

The & operator, in this context, does a "multipitch" bit. Then it takes the number contained in each of the variables and individually tests each one resulting in 1 only when the analyzed bit is 1 in the two variables at the same time. Since you probably have a current variable like flag and the only possible values should be 0 and 1 in those variables, it works, because only the least significant bit varies, all others are always 0.

But if this variable were to have other values than 0 and 1, and the typing allows this, it would no longer work, or worse, in some cases it would work and others would not. It would be confusing for an experienced programmer, imagine for a beginner. That is why it is better to use the correct semantics at all times. In this case it would be.

if (!(errS && errE))

So the number will be guaranteed to be converted to 1 if it is not 0.

Then the result of the internal expression will only be 1 when the two variables are different from 0.

The ! is a Boolean result inverter. So if the result of the expression in parentheses is 1, it will consider the general result as 0 and if the partial result is 0, the final result will be 1.

The same goes for the other simpler expressions in which the inversion already occurs directly in the variable. If the variable is 0, the result will be 12, if the variable is anything other than 0, the result will be 0.

Remembering that if executes whenever the final result of the expression contained in its condition is 1. Also remembering that the condition is any expression, even a if (1) can be used, of course meaningless because if would always execute. Contrary to what many people think does not need to have a comparison within the condition of if , it must have a Boolean value, that is, or 0, or 1, how it will be obtained is another question.     

04.04.2018 / 15:19
0

Make if(!errS) is the same as if(errS == 0) , if for example the type of variable errS is int . This means that the variable errS is empty. I hope I have helped.

    
04.04.2018 / 09:00