Reputation: 1319
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?
Upvotes: 5
Views: 434
Reputation: 4145
People perform NULL
checks on pointers to determine whether or not the pointer is valid. We would need to call a function to determine whether or not a struct
was valid, and the answer would depend on knowledge of the exact contents and their meaning. For example...
typedef struct
{
int numOfStudents;
} School;
int null_check(School* item)
{
/* This test assumes that a School is invalid if it has no students.*/
return (!item || !item->numOfStudents);
}
/*...*/
School s;
/*...*/
if(null_check(&s)) {
printf("null");
}
Note that while a pointer is either pointing at something or not, the question of whether a data structure is valid is potentially much more complex, and should not be confused with the question of whether the structure has been initialized or has every data member set to zero.
Upvotes: 1
Reputation:
NULL is used only by pointers. For example something like school *s == NULL
would be valid since s
is a pointer to type school
. However in your case s
is not a pointer therefore it cannot be compared to NULL.
Upvotes: 1
Reputation: 123468
NULL
applies to pointer types, and s
isn't a pointer, it's an instance of the School
type.
If you declared s
as a pointer to School
, such as
School *s;
then the null check would make sense:
if ( s )
{
// s points to a valid instance of School
}
Upvotes: 2
Reputation: 104539
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.
Upvotes: 7
Reputation: 25286
A struct consists of data elements. Each element can be null (if appropriate for the type of element), but the struct itself cannot be [compared to] null, even if it has only one data element.
Upvotes: 1
Reputation: 223972
NULL
is a special pointer value that is defined to not point anywhere. You can't check if s
is NULL
because s
is not a pointer.
If your intent is to see if s
has been initialized, you can't do that either because there's no special value that tells you that a variable has been initialized. For example a uninitialized int
could contain 0, 1, 34634, -265356657, or any other value.
Your best bet is to initialize the variable with a known value and check for that.
School s = { -1 };
if (s.numOfStudents == -1) {
printf("not used yet\n");
}
Upvotes: 1
Reputation: 7482
Because null
applies to pointers and s
is not a pointer.
BTW, s
is an automatic object that lives on the stack and cannot be null.
Upvotes: 1