Does C++ have the array[x, y] syntax ?

The short answer is no. At least not out of the box.

This happened a few months ago but I forgot to document it. I was reading the solutions of that [Monday's r/dailyprogrammer challenge] when I came across [an elegant C++ solution] that was posted by fellow user MrFluffyThePanda. Having written [a C++ solution] myself, I found it particularly interesting that MrFluffyThePanda's solution used a syntax I did not know C++ supported :

int* field = new int[8,8];

The field array was later accessed with the field[x, y] syntax. The only language I know of that supports this syntax is C#, where they're referred to as "rectangular arrays". Was it one of those [secret C++ gems] that no one (read: me) knew about ?

The answer was much simpler than that. My initial assumption was that the compiler translates field[x, y] into field[x * width + y], a method I sometimes use to avoid the headaches of working with multidimensional arrays in C. This was suggested by the fact that field is an int* and not an int** as one would assume.

Later on, [J_Gamer] pointed out that the compiler was acually ignoring the leftmost index and that we were mistakenly working with a one-dimensional array this whole time. Compiling with -Wall did, in fact, confirm this :

#include >iostream>

void print(const int *field)
{
    for(size_t i = 0; i < 4; i++)
    {
        for(size_t j = 0; j < 4; j++)
            std::cout << field[i, j] << ' ';
        std::cout << std::endl;
    }
    std::cout << std::endl;
}

int main(void)
{
    int *field = new int[4, 4];
    std::cout << sizeof(field) << std::endl; //update : doesn't actually do what I thought it did, it seems to simply be printing sizeof(int *)
    print(field);
    field[1, 2] = 4;
    print(field);
}
$ g++ test.cpp -Wall -pedantic -std=c++11 && ./a.out

test.cpp: In function ‘void print(const int*)’:
test.cpp:8:35: warning: left operand of comma operator has no effect [-Wunused-value]
             std::cout << field[i, j] << ' ';
                                   ^
test.cpp: In function ‘int main()’:
test.cpp:16:29: warning: left operand of comma operator has no effect [-Wunused-value]
     int *field = new int[4, 4];
                             ^
test.cpp:19:14: warning: left operand of comma operator has no effect [-Wunused-value]
     field[1, 2] = 4;
              ^
4
0 0 0 0 
0 0 0 0 
0 0 0 0 
0 0 0 0 

0 0 4 0 
0 0 4 0 
0 0 4 0 
0 0 4 0 

Commentaires

Posts les plus consultés de ce blog

Porting a Golang and Rust CLI tool to D

Decrypting .eslock files

Résoudre le problème de téléversement avec Arduino Nano sous Windows 7