Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

179
Views
Difference between expression: while(str[i] != '\0') and while (str[i])

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.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!