0

Why this code compiles and returns 1?

int main(int ac, char* av[])
{
    return ac[av] == 0;
}
  • You sure it's not av[ac] == 0 ? – Tilak Madichetti Apr 09 '17 at 13:18
  • 4
    @TilakMaddy Both are correct. – DeiDei Apr 09 '17 at 13:19
  • 2
    There must be another question answering this, anyhow (for the short space allowed in a comment): `pointer[i]` is the same than `*(pointer + i)` which is the same than `*(i + pointer)` which is the same than `i[pointer]`. – peppe Apr 09 '17 at 13:20
  • @TidyMaddy Yes, I'm sure – Radosław Panuszewski Apr 09 '17 at 13:20
  • 3
    `ac[av]` is equivalent to `av[ac]`. Since `ac` (or `argc`) is the number of arguments passed in `av` array, you'll always get out-of-bounds access which is _undefined behavior_. However, it is likely that first pointer past `av` (again, it should be called `argv`) is null pointer, comparison returns true value which is coded as `1`. – myaut Apr 09 '17 at 13:20
  • @myaut, `av[ac]` is defined to be 0/null. – chris Apr 09 '17 at 13:23
  • 1
    @myaut: absolutely not, `argv[argc]` is guaranteed to be 0. See http://eel.is/c++draft/basic.start.main#2 – peppe Apr 09 '17 at 13:23

0 Answers0