0

I have the following code:

char alfabeto[] = {'a','b','c','d','e','f','g','h','i','j','k','l','m',
                   'n','o','p','q','r','s','t','u','v','w','x','y','z'};  

int i = 0;

printf("|");

do
{
    printf("%c |",alfabeto[i]);
    i++;
}while(alfabeto[i]!= '\0');

With NULL I get the following warning:

warning: comparison between pointer and integer [enabled by default] in C

But with '\0' it compiles OK. I know which '\0' is used for terminating char strings and NULL is used for comparison with pointers. But do they not have the same value?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Adrián Romero
  • 620
  • 7
  • 17
  • 2
    Note that your `alfabeto` character array is not null terminated (which means it isn't a string), so there is no guarantee about when the loop will terminate, or what garbage will be printed after `z`. – Jonathan Leffler Nov 13 '14 at 06:47

3 Answers3

3

In most implementations NULL and '\0' have the same value: both are zero. The difference is in the data type: NULL is a pointer, while the other is an int. It doesn't really make sense to compare pointers with anything that's not a pointer, and that's why the compiler gives you a warning.

Joni
  • 108,737
  • 14
  • 143
  • 193
2

They have the same value, but are different in type.

  • \0 is the same as 0
  • NULL is implementation-defined, but usually the same as (void*)0.

You should always look towards using expressions with the right type.

glglgl
  • 89,107
  • 13
  • 149
  • 217
1

NULL has void* as type, but '\0' is of type int.

void* are pointers, so 8 bytes on my machine. int is 4 bytes.

In C++ '\0' is a char of 1 byte

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547