-1

I am learning C from a textbook, and I stumbled onto the code of a function, where the following part had little explanation to what it does. It looked something like this:

int func(char *a, char *b) {
    if(!a || !b)
        return 0;
    return 1;
}

My understanding is it checks that a and b are not null? Is this correct? Any help is welcome for this beginner :)

Weather Vane
  • 33,872
  • 7
  • 36
  • 56
anInputName
  • 439
  • 2
  • 12

3 Answers3

4

! is the logical not operator.

The if condition !a || !b is true if either a or b are zero, i.e. NULL pointers. Then the func returns 0 in that case, 1 otherwise:

a        b        condition  func
null     null     true       0
null     non-null true       0
non-null null     true       0
non-null non-null false      1

It is easier to understand if you negate the condition and swap the return values:

int func(char *a, char *b) {
    if(a && b)
        return 1;
    return 0;
}

Since in C the relational operators give their result as an int, i.e. 0 for false and 1 for true, you can simplify further to:

int func(char *a, char *b) {
    return a && b;
}
Acorn
  • 24,970
  • 5
  • 40
  • 69
0

Not exactly. When a is null or b is null then the logical NOT operator will cause the if conditional to evaluate as true and the return value is zero, otherwise the code returns 1 indicating that either a or b is not null.

slevy1
  • 3,797
  • 2
  • 27
  • 33
-1

The ! operator in most programming languages reverses the logic(or the not operator). i.e.(From True to False or vice versa)

For example:

a=True;
if(!a) {
    return 1;
}else {
    return 2;
}

Output is 2. So in this case, you are saying if not A OR not B, return 0.