12

Ada has nice feature of and then statement used in the if condition in addition to the Boolean and operator. This allows for checking if, e.g., the object is not null before accessing it like so:

if Object /= null and then Object.Value > 5 then
   -- do something with the value
end if;

Is there a way to express a similar behaviour in C++ w/o using a nested if?

NeoSer
  • 527
  • 3
  • 16
  • 2
    just use if ((obj != null) && (object.value > 5)). c++ will evaluate left to right and stop evaluating && when the first in the chain is false – skeller May 16 '19 at 19:01
  • 1
    The `and` or `&&` operator has fixed order of evaluation – JVApen May 16 '19 at 19:01
  • `if (foo) foo->bar()` ?? – Jesper Juhl May 16 '19 at 19:11
  • In Ada, there is also an `and` operator, which is a Boolean and operator as explained here: https://en.wikibooks.org/wiki/Ada_Programming/Keywords/and – NeoSer May 16 '19 at 19:15
  • 4
    thanks for the link. In C++ `and` corresponds to the ada `and then` and I wouldnt even know from the top of my head to write a "non-shortcircuiting and" ;) – 463035818_is_not_an_ai May 16 '19 at 19:20
  • 1
    @formerlyknownas_463035818 Thank you for the comment. Added the link to the question. – NeoSer May 16 '19 at 19:27
  • 1
    @formerlyknownas To prevent short circuiting, you could assign the evaluation of the operands to two different named variables and then perform the and on the results. –  May 16 '19 at 19:28

1 Answers1

17

Well, Object cannot be NULL in C++ in your code as it seems not to be a pointer. If it were a pointer you could say:

 if (Object && Object->Value > 5 ) {
       // do something
 }

In C++ the && operator performs "short-circuited evaluation" - the evaluation stops if a left-most operand evaluates to false.

  • To expand on Neil's answer, the || operator also does short-circuit evaluation. For most other operators, the order of evaluation of the operands is unspecified. – Dave May 16 '19 at 19:27
  • @Dave comma-operator and conditional-operator also specify evaluation order. Also the `.` and `->` operator. I'm sure there are others that I have forgotten :-) –  May 16 '19 at 19:31
  • 1
    @NeoSer just make sure not to use `&` instead as it does not have short-circuit, you may prefer use alias `and` instead to avoid confusion – Slava May 16 '19 at 19:41
  • 2
    Why do you say it doesn't seem to be a pointer (or access value, as its called in Ada)? Ada can easily have an variable called `Object` of an access type: `type Foo is access Bar;` and then `Object : Foo;` – egilhh May 17 '19 at 08:07
  • 2
    To expand on @egilhh’s comment, `Object.Value` is a legal dereferencing, shorthand for `Object.all.Value` – Simon Wright May 19 '19 at 08:16