user11954200
user11954200

Reputation:

Detecting end of character stream

Why is the following loop:

for (int i=0; string[i] != 0; i++)

Often written as the following:

for (int i=0; string[i] != '\0'; i++)

If they would evaluate to the same thing, why would someone use the \0 in the above? Is there any advantage in that or it is the same thing?

Upvotes: 2

Views: 72

Answers (3)

brokenfoot
brokenfoot

Reputation: 11629

'\0' is has ASCII value 0. so,

ASCII('\0') == 0 // same thing

Edit:
where: ASCII(): some function that returns ASCII value. C doesn't have such function (although you can just print char as %d to get its ASCII value).

Upvotes: -1

John Bayko
John Bayko

Reputation: 1091

The main difference is type. 0 is an int, '\0' is a char. Very old compilers would insert conversion code because of the size difference, so using '\0' was more efficient, but that hasn't been the case for a long time.

Still, some people prefer using '\0' to make the type of the comparison explicit.

Upvotes: -1

Steve Summit
Steve Summit

Reputation: 47962

It is the same thing. There is no particular advantage. The string[i] != '\0' form emphasizes that we're looking at characters. But the further simplification for (int i=0; string[i]; i++) would work just as well also.

It's similar with pointers. You can write p != NULL, or p != 0, or just p. The first form emphasizes that we're talking about a pointer. But it's a matter of style, not correctness.

Upvotes: 3

Related Questions