More on arrays

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?).

Onwards to another characteristic of arrays, which you are unlikely to encounter.. 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];

2 thoughts on “More on arrays

    1. 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

Your email address will not be published. Required fields are marked *