Difference between expression: while(str[i] != '\0') and while (str[i])
Asked Answered
L

1

5

Is there any difference between those 2 expressions when it comes to checking whether or not we come to the end of the string?

while(str[i] != '\0') 

And

while (str[i])

Where str has type char* and i is an integer.

Limann answered 2/2, 2022 at 8:7 Comment(1)
The first is self-documenting code means "while the character is not null terminator" and the second can either mean that, or it can mean "This is some nonsense since I actually meant to take the address of the item and compare against null".Cosme
P
11

In fact there is no difference. Any expression that evaluates to a non-zero value is considered as a logical true expression. And an expression that evaluates to zero is considered as a logical false expression.

From the C Standard (6.8.5 Iteration statements)

4 An iteration statement causes a statement called the loop body to be executed repeatedly until the controlling expression compares equal to 0. The repetition occurs regardless of whether the loop body is entered from the iteration statement or by a jump.1

Pay attention to that in C an expression with an equality operator has as value either 1 or 0.

So the expression str[i] != '\0' yields 1 (non-zero value) if the relation is true or -0 otherwise.

In C++ the type of such an expression is bool and its value is either true or false.

From the C++ 14 Standard (4.12 Boolean conversions)

1 A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true. For direct-initialization (8.5), a prvalue of type std::nullptr_t can be converted to a prvalue of type bool; the resulting value is false.

Pavement answered 2/2, 2022 at 8:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.