cplusplus.co.il

More on arrays

Posted 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);
}
Advertisements

2 Responses to "More on arrays"

I think that 2[x] won’t work for an array of non chars…

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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: