Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is '\0' guaranteed to be 0?

Tags:

I wrote this function in C, which is meant to iterate through a string to the next non-white-space character:

char * iterate_through_whitespace(unsigned char * i){
    while(*i && *(i++) <= 32);
    return i-1;
}

It seems to work quite well, but I'm wondering if it is safe to assume that the *i will be evaluated to false in the situation that *i == '\0', and it won't iterate beyond the end of a string. It works well on my computer, but I'm wondering if it will behave the same when compiled on other machines.

like image 885
Paul Avatar asked Sep 25 '11 22:09

Paul


People also ask

Are '\ 0 and 0 the same in C?

Each array is terminated with '\0' or null character but if we store a '0' inside a string both are not same according to the C language. '0' means 48 according to the ASCII Table whereas '\0' means 0 according to the ASCII table.

Is null and '\ 0 the same?

Recently a client asked me what is the difference between NULL and 0 values in Tableau. The answer to that is rather simple: a NULL means that there is no value, we're looking at a blank/empty cell, and 0 means the value itself is 0.

What is the difference between 0 and '\ 0?

0 is a literal which yields a numeric value of zero. '\0' is a literal which gives a character with numeric value of zero.

IS NULL always defined as 0 zero )?

No, but zero is always NULL .


2 Answers

The standard says:

A byte with all bits set to 0, called the null character, shall exist in the basic execution character set; it is used to terminate a character string.

like image 107
cnicutar Avatar answered Nov 02 '22 22:11

cnicutar


Yes -- but in my opinion it's better style to be more explicit:

while (*i != '\0' && ...

But the comparison to 32 is hardly the best approach. 32 happens to be the ASCII/Unicode code for the space character, but C doesn't guarantee any particular character set -- and there are plenty of control characters with values less than 32 that aren't whitespace.

Use the isspace() function.

(And I'd never name a pointer i.)

like image 44
Keith Thompson Avatar answered Nov 02 '22 22:11

Keith Thompson