Integers and pointers in Boolean expressions
suggest changeAny integer or pointer can be used in an expression that is interpreted as a “truth value”.
int main(int argc, char* argv[]) {
if (argc % 4) {
puts("the number of arguments is not divisible by 4");
} else {
puts("the number of arguments is divisible by 4");
}
...
The expression argc % 4 is evaluated and leads to one of the values 0, 1, 2 or 3. The first, 0, is the only value that is “false” and brings execution into the else part. All other values are “true” and go into the if part.
double* A = malloc(n*sizeof *A);
if (!A) {
perror("allocation problems");
exit(EXIT_FAILURE);
}
Here the pointer A is evaluated and if it is a null pointer, an error is detected and the program exits.
Many people prefer to write something like A == NULL instead, but if you have such pointer comparisons as part of other complicated expressions, things quickly become difficult to read.
char const* s = ....; /* some pointer that we receive */
if (s != NULL && s[0] != '\0' && isalpha((unsigned char)s[0])) {
printf("this starts well, %c is alphabetic\n", s[0]);
}
To check this, you have to scan a complicated expression and be sure about operator precedence.
char const* s = ....; /* some pointer that we receive */
if (s && s[0] && isalpha((unsigned char)s[0])) {
printf("this starts well, %c is alphabetic\n", s[0]);
}
is relatively easy to follow: if the pointer is non-null, check whether the first character is non-zero and then whether it is a letter. The cast to unsigned char matters when plain char is signed; a negative character value is not a valid isalpha argument. n in the allocation above is the element count.