0

I recently noticed that it's possible to verify the existence of a variable (e.g pointer type in C) and just after, verify an element inside of that variable (e.g dereferencing the pointer) in a same control flow (e.g if statement).

Before noticing

if (my_array)
{
    if (my_array[n])
    {
        //Do something
    }
}

After noticing

if (my_array
     && my_array[n])
{
    //Do something
}

I was a little bit suprised about that behaviour, and I used valgrind to see if the system has been "kind" with me during the execution of the program, but valgrind was straight and said that I've got

ERROR SUMMARY: 0 errors from 0 contexts.

So I whish to know if the compiler only refers to operators, in order to create a sort of flowchart, or it's another type of evaluation. And does every compilers use the same type of behavior ?

sepp2k
  • 363,768
  • 54
  • 674
  • 675
Jankov_n
  • 103
  • 1
  • 11
  • 3
    Boolean operators are short circuiting and have defined order of evaluation in C: http://stackoverflow.com/questions/628526/is-short-circuiting-boolean-operators-mandated-in-c-c-and-evaluation-order – Ilja Everilä May 20 '17 at 14:24
  • valgrind wouldn't help you detect a problem here, if there were one. Valgrind only detects what happens; not what could happen if undefined behaviour turned out differently. – rici May 20 '17 at 14:50
  • Thanks to short-circuiting of logical operators (link by IljaEverilä) - which is guaranteed by the C standard - your two samples of code are functionally equivalent. The only way for behaviour to be incorrect is for `n` to be a bad index with `my_array` - which your code does not check. – Peter May 20 '17 at 15:02

0 Answers0