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

  • A+

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?


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.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

目前评论:1   其中:访客  1   博主  0

    • Torsten Torsten 0

      That’s because only a pointer (e.g. to a struct) can be NULL.
      The “School s;” already allocates memory for the structure (or places it on the stack), so there is no pointer.

      School *s = NULL;
      if( s )
      printf(“yup, null\n”);

      would work.