Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't structs be compared for NULLness in C?

Tags:

c

null

struct

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?

like image 330
hitchhiker Avatar asked Oct 31 '18 14:10

hitchhiker


People also ask

Why we Cannot compare structures 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.

Why we Cannot compare structure?

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 .

Can structures be compared using ==?

Actually yes, but the == operator will only check if the two references of structs point to the same struct.

Can we compare 2 structures in C?

C provides no language facilities to do this - you have to do it yourself and compare each structure member by member.


1 Answers

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.

like image 172
selbie Avatar answered Oct 01 '22 19:10

selbie