top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

why (myarr[2] == 2[myarr]) is true in C/C++?

+3 votes
354 views

See the following code -

main()
{
  char myarr[]="My Name is King khan";
  if (myarr[2] == 2[myarr])
   printf("Strange Behavior");
}

Output is

Strange Behavior

Can someone explain the reason why why (myarr[2] == 2[myarr]) is true?

posted Oct 8, 2014 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button
a[b] means *(a+b) which is same as b[a] i.e. *(b+a) so condition is matching.

1 Answer

+1 vote

Salil's explanation is correct just adding my view point here -
As per K&R-
a[b] means *(a + b)

Therefore myarr[2] means *(myarr + 2)
and 2[myarr] is *(2 + myarr)

and we know these are equal.

This is the direct artifact of arrays behaving as pointers, "myarr" is a memory address. "myarr[2]" is the value that's 2 elements further from "myarr". The address of this element is "myarr + 5". This is equal to offset "myarr" from "2" elements.

answer Oct 9, 2014 by Vikram Luthra
...