-1

I came across this code I have no clue what it is doing

// ptr is a pointer to an int
if (2[ptr] == 5){
    // do something
}

I did some of my tests but no matter what value I pass into ptr, 0, negatives, positives, 2[ptr] always evaluates to 0. I am surprised it actually compiles. Can someone explain what this expression is ?

Bobby
  • 1,511
  • 1
  • 15
  • 24

1 Answers1

2

2[ptr] is the same as ptr[2] (more or less). Somebody is playing a little joke on you.

As for why it always evaluates to 0, that depends on the rest of the program, which we cannot see.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055