Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

c

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 could do this with any type of array, so I cheated and assumed that it was an array of integers and wrote this function:

int GetHundredthElement(int *array) {
  return array[100 - 1];
}

(the - 1 is there because arrays are zero-indexed)

I asked him how to make a function that would work for any type of array. He told me there was a simple way to do it:

int GetHundredthElement = 100 - 1;

and that this "function" could be called like this:

GetHundredthElement[array];

I tried it, and it worked, but doesn't look like a function to me because it uses bracket notation, which isn't how function calls are written in C. I don't really understand exactly what this code is doing or how it's doing it. What's going on here?

like image 646
Peter Olson Avatar asked Nov 28 '22 12:11

Peter Olson


1 Answers

It's not a function, it simply takes advantage of a little-known C fact that array indexes can be interchanged. All the x[y] notation really means is that you're accessing the xth offset of the y array. But you could just as easily write y[x] in your case and get the same result.

99[array] and array[99] are interchangeable and mean the same thing. By declaring GetHundredthElement to be 99, your friend played a neat trick :)

You CAN however write a generic function to get the hundredth element of an array fairly easily using C++ templates (not C).

like image 165
Mahmoud Al-Qudsi Avatar answered Dec 16 '22 12:12

Mahmoud Al-Qudsi