Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the null terminating character as null pointer in C [duplicate]

Tags:

c

#include <stdio.h>

int main(){
 int *p = '\0';
 if (p == NULL){
   // this block will get executed.
 }
 return 0;
}

I have read that 0, NULL and \0 are all equal to the integer constant 0 in C. So is the above code technically correct in setting and checking for a NULL pointer? I guess it still needs to be avoided as \0 is mainly used to terminate strings and its usage here is confusing?

like image 452
Dan Avatar asked Nov 26 '22 17:11

Dan


2 Answers

'\0' is an integer zero.

All three do exactly the same.

int *p = NULL;
int *p = 0;
int *p = '\0'; 

but the last two may emit the warning.

like image 145
0___________ Avatar answered Dec 21 '22 09:12

0___________


The best way to describe is that a pointer can be a zero, indicating its functionally pointing to nothing (which isn't true: it's actually pointing at memory spot zero). But there are many ways to represent a zero, and NULL is one of those ways. So technically, any way you write the zero is technically legally as long as the compiler interprets it as "zero".

FYI, some people write if statements in reverse to protect against an accidental assignment if you forget an equal sign:

if (NULL == p){
like image 32
Wes Hardaker Avatar answered Dec 21 '22 10:12

Wes Hardaker