Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why assert(str!=NULL) does not return an error?

Why did this not print an assert error?

This is my code:

#include<assert.h>
#include<stdio.h>

int main(){
    int n =12;
    char str[50] = "";
    assert(n>=10);
    printf("output :%d\n",n);
    assert(str!=NULL);
    printf("output :%s\n",str);
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

char str[50] = "";

This makes str into an array of 50 chars, and initialises the memory to all zeroes (first byte explicitly from "" and rest implicitly, because C does not support partial initialisation of arrays or structs).


assert(str!=NULL);

When used in an expression, array is treated as pointer to its first element. The first element of the array very much has an address, so it is not NULL.


If you want to test if the first element of the array is 0, meaning empty string you need

assert(str[0] != '\0');

You could compare to 0, or just say assert(*str);, but comparing to character literal '\0' makes it explicit to the reader of the code, that you are probably testing for string-terminating zero byte, not some other kind of zero, even if for the C compiler they’re all the same.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading