0

I have found online this question: (original post: https://medium.com/@vardanator/why-cs-students-must-learn-c-as-their-main-programming-language-6d3b4f8720bd)

What is output of:

int arr[] = {1, 2, 3, 4};
int* p = arr;
int* k = p;
std::cout << (*(k + 2) + 1[p] + *(0 + arr)) << std::endl;

I think I understand correctly the *(k + 2) and the *(0 + arr), but I really cannot understand how 1[p] can be valid and what it really means.

Any simple explanation?

I guess one should not write code like this ever (or am I wrong? any case when writing something like that would be good, readable code?), but just curious.

scohe001
  • 15,110
  • 2
  • 31
  • 51
Zorglub29
  • 6,979
  • 6
  • 20
  • 37
  • TL;DR of the dupe: `1[p]` is the same as `p[1]`. But yeah, don't write code like that, it confuses people and confusion in a code base is a bad thing. – NathanOliver Jan 24 '20 at 14:45
  • `p[1]` --> `*(p + 1)` --> `*(1 + p)` -->`1[p]` – Paul Evans Jan 24 '20 at 14:46
  • The expression `E1[E2]` is identical (by definition) to `*((E1)+(E2))`. – adziri Jan 24 '20 at 14:49
  • Ok, thanks ! Sorry for missing the solution, but googling 5[a] was not easy ^^. Any idea how to make this sort of stuff easily searcheable and / or what should I have searched for? – Zorglub29 Jan 24 '20 at 14:50
  • @Zorglub29 you can open C++ ISO and read about it, for example from here http://eel.is/c++draft/expr.sub#1 – adziri Jan 24 '20 at 14:51
  • Ok, that would have been a long shot ^^ . Thanks for your help, that was much simpler. – Zorglub29 Jan 24 '20 at 14:54

0 Answers0