I have the following struct:
typedef struct School
{
int numOfStudents;
} School;
For example if I have a struct:
School s;
I want to check whether the struct is null like this:
if(s) {
printf("null");
}
This will not compile and error message is as follows:
error: used struct type value where scalar is required
Why can't I check structs for NULLness inside if statement in C?
Because the operator == is not aware of all the members of the structure it would need to compare, you are! You can't compare strings either, in C - at least, not with '==' or equivalent.
We should not compare structures because of the holes between the member fields of a structure. Comparing the structures themselves as variables won`t work. Compare each element of the structure. You should not compare structure variables directly,using *pointer variables comparing two varables is possible .
Actually yes, but the == operator will only check if the two references of structs point to the same struct.
C provides no language facilities to do this - you have to do it yourself and compare each structure member by member.
In the case of:
School s;
s
is definitely not NULL, because it is not a pointer. It is however, an uninitialized instance of a struct, and the value of s.numOfStudents
is undefined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With