13

If I need to null-terminate a String, should I rather use \0 or is a simple 0 also enough?

Is there any difference between using

char a[5];
a[0] = 0;

and

char a[5];
a[0] = '\0';

Or is \0 just preferred to make it clear that I'm null-terminating here, but for the compiler it is the same?

Spikatrix
  • 20,225
  • 7
  • 37
  • 83
erg
  • 1,632
  • 1
  • 11
  • 23

5 Answers5

15

'\0' is an escape sequence for an octal literal with the value of 0. So there is no difference between them

Side note: if you are dealing with strings than you should use a std::string.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
10

Use '\0' or just 0?

There is no difference in value.
In C, there is no difference in type: both are int.
In C++ they have different types: char and int. So the edge goes to '\0' as there is no type conversion involved.

Different style guides promote one over the other. '\0' for clarity. 0 for lack of clutter.

Right answer: Use the style based on your group's coding standards/guidelines. If you group does not have such guideline, make one. Better to use one than have divergent styles.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
8

'\0' is exactly the same as 0 despite of the type. '\0' is just a representation as a char literal. The type char can be initialized from plain int literals though.

So it's actually impossible to tell what's better, just keep in mind to use it consistently in your code.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
6

Both will generate the same machine code, as 0 will be converted to the character value 0, and '\0' is just another way of writing the character value 0. The latter is clearly a character, so it will show that you didn't accidentally mean to write '0' instead, but other than that, it's exactly the same thing in the end.

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227
1

It's the same thing. Look at the ascii table.

It's better from my point of view to use '\0' because you explicity say that the end of string.

That help when you read your code (like using NULL for pointer instead of 0).

Tom's
  • 2,448
  • 10
  • 22