Posted by: rmn on: 06/09/2009
Let’s have a better look at native arrays.
Here’s a piece of code with its compiler transformation:
char x[] = "test"; x[1]; // is basically translated to: *(x+1)
So it should be just alright to write the following code:
if (x[2] == 2[x]) std::cout << "Always true!" << std::endl;
And indeed, the code is perfectly fine and the given if-statement will always be evaluated to a true value.
Let’s try something even more interesting. How about:
std::cout << 3["hello"] << std::endl;
This odd line of code would print the 4th letter of the given word to the standard output (can you see why?).
And a little extra on arrays.. As already pointed out by aSk, arrays can easily be passed by reference using this handy syntax:
void f (int (&x)[5]) {
// int x[5] passed by reference
}
int main () {
int x[5];
f(x);
}
08/09/2009 at 19:02
I think that 2[x] won’t work for an array of non chars…
08/09/2009 at 19:08
Sure it will. The following works:
int x[] = {1,2,3,4,5}; std::cout << 2[x] << std::endl;The term *(2+x) is ofcourse calculated using pointer arithmetics, meaning its actually *(x+2*4) when we’re dealing with 32bit (4byte) integers.