3

I don't know what happened to this line num && *num == maxNum. Why var && *var can be used to judge the max bound? I really need to someone to explain this...

void func(...,size_t *_Nullable num,...){

    size_t num_=0;
    somethingHappen_get_num(&num_);

    if(num){
        *num =  num_;
    }

    if (num && *num == maxNum) { //why???????????
        Log_print("num is too big");
        return Error;
    }
}
Mat
  • 202,337
  • 40
  • 393
  • 406
sin
  • 33
  • 3
  • 3
    num is a pointer, `if(num is not null and num is pointing to a number that is equal to maxNum){do stuff}` – hanshenrik Aug 13 '19 at 05:27
  • Thanks! @hanshenrik '==' priority is bigger than '&&', so I misunderstanding! Your comment let me be clear!! – sin Aug 13 '19 at 05:34
  • It becomes easier to read and self-documenting when the code is written more explicitly: `if ( (num != NULL) && (*num == maxNum) )` – Lundin Aug 13 '19 at 10:48

2 Answers2

5

since num is of size_t *_Nullable num i.e pointer type, so you should always check whether its empty i.e NULL or have some valid data, if its valid, then only its safe to de reference(*num) it.

Here

if (num && (*num == maxNum)) { } /* safe & correct, && means if 1st operand is valid then only check 2nd operand which is recommended here */

the condition check is correct and safe as first its checking if num is not NULL, if that's true then only its checking *num == maxNum i.e something is there in num so that you can do *num.

Consider below scenario

if (num || (*num == maxNum)) { } /* bad practice, don't do it */

above condition check creates issue if num is NULL, due to logical OR operand || it will check second operand as first is false and it causes crash when it perform *num.

Achal
  • 11,821
  • 2
  • 15
  • 37
2

You could also write:

if ((num != 0) && (*num == maxNum))

Maybe this makes it clearer.
First you check if num is not NULL. If this condition is true (and only then!) you will dereference the pointer and check *num == maxNum.

Mike
  • 4,041
  • 6
  • 20
  • 37