0

Today I wanted to propose to students a very short and stupid code as follows

# include <iostream>

int main()
  {
   int a[] {10, 20, 30, 40};

   for(int k=0; k != 4; ++k) std::cout << ++a[k] << ' ';

   std::cout << std::endl;

   }

in order to show how the ++ prefix operator acts in an expression.

I inadvertently mistyped the code, ending up with the following line, in place of the one shown above:

for(int k=0; k != 4; ++k) std::cout << ++k[a] << ' ';

shortly: swapping k and a in the operand of ++.

Well... not only this is compiled, but it gives also the correct results. How this could be understood? Is the index of the loop interpreted as an iterator over the array a? Or what else?

GSi
  • 649
  • 3
  • 10
  • Yeah it's a funny quirk of the language that there's no difference if you switch the array name and the index. – AndyG Nov 08 '16 at 16:06
  • Enforce good coding standards, always use `{` and `}` after `for` loops. This will help reduce injected defects that are hard to trace. – Thomas Matthews Nov 08 '16 at 16:10
  • @ThomasMatthews how would braces help here? – NathanOliver Nov 08 '16 at 16:11
  • @NathanOliver: It's not a matter of helping or not. Since the OP is teaching students, its a good idea to start good habits early. See the MISRA coding guidelines and other guidelines. Braces help issues where the author wants a second or third line but forgets about the `;`. Search StackOverflow for examples. – Thomas Matthews Nov 08 '16 at 16:15
  • OK, thanks a lot. Meanwhile I have found the answer in the clause 8.3.4.6 of the C++ standard. – GSi Nov 08 '16 at 19:43

0 Answers0