1

(this question is an exact copy of Is compound if checking for null and then other condition in C always safe? but about C++, not C. It was pointed out that the question should be more specific).

I have been using the following type of if condition for a lot of time.

char* ptr = ...;
if (ptr != NULL && ptr[0] != '\0') // <=== is this always safe?
{ /* ... */ }

It relies on ptr != NULL being checked before ptr[0] !='\0'.

Is it safe under all standards, compilers, architectures? Or is there a possibility that ptr[0] != '\0' will be checked before ptr != NULL?

Community
  • 1
  • 1
Dariusz
  • 21,561
  • 9
  • 74
  • 114
  • Thanks for re-posting. That was the correct thing to do (separate languages) but this question has already been asked many times in the past. :) – Lightness Races in Orbit Feb 14 '14 at 10:51
  • 1
    @LightnessRacesinOrbit yes, I've seen the close suggestions and it's true, that's the same question. It's OK if it gets closed. I won't delete it though, it's yet another way to rephrase the same problem, so it'll attract more google hits. – Dariusz Feb 14 '14 at 10:58

2 Answers2

4

It is safe in this case. Short-circuit evaluation means that the RHS of the && operator will only be evaluated if the first is true.

C++ allows to override bool operator && for user defined types. Using an overriden && does not follow short-circuit evaluation, so the safety is lost. It is rarely a good idea to overload this operator.

Here's an example showing the behaviour of an overloaded && operator:

struct Foo {};

bool operator && (const Foo&, const Foo&) { return true; }

#include <iostream>

Foo make_foo()
{
  std::cout << "making foo\n";
  return Foo();
}

int main()
{
  make_foo() && make_foo(); // evaluates both expressions
}
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
0

It is safe as long as operator && is not overloaded

C++ standard draft says (N3337 - 5.14 Logical AND operator):

The && operator groups left-to-right. The operands are both contextually converted to type bool (Clause 4). The result is true if both operands are true and false otherwise. Unlike &, && guarantees left-to-right evaluation: the second operand is not evaluated if the first operand is false.

user694733
  • 15,208
  • 2
  • 42
  • 68