This doesn't look like a function. What is this?

前端 未结 5 2012
無奈伤痛
無奈伤痛 2021-01-06 05:02

A friend asked me to write a function in C to return the 100th element of an array. I\'m not very familiar with C, so I wasn\'t sure how to make a generic function that coul

5条回答
  •  余生分开走
    2021-01-06 05:11

    You are right about the fact that GetHundredthElement is not a function-- it is, as you would expect, an integer.

    However, this illustrates a surprising ability in C where you can reverse the order of your array access!

    assert(a[5] == 5[a]);
    

    This is because an array access can be implemented in pointer arithmetic:

    assert(a[5] == *(a+5));
    assert(*(a+5) == *(5+a));
    assert(*(5+a) == 5[a]);
    

提交回复
热议问题