Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Is it legal to declare pointers and array on the same line?

Tags:

c++

The following code works but I have been told that it doesn't compile with gcc 3.4.2 with Visual C++ 2010 and may be illegal:

int ar1[]{0,1,2,3,4,5,6,7,8,9},
    *ptr1 = ar1,
    ar2[]{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18},
    *ptr2 = ar2;

Apparently you need to make some modifications for it to work (something like that):

int ar1[]{0,1,2,3,4,5,6,7,8,9};
int *ptr1 = ar1;
int ar2[]{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18};
int *ptr2 = ar2;

Is that right? Can't arrays and pointers be declared together?

(The code compiles fine on QT + gcc 4.8)

like image 383
2013Asker Avatar asked Dec 07 '22 06:12

2013Asker


1 Answers

The declaration in question uses C++11 initialization syntax. It is not syntactically correct from the point of view of pre-C++11 compiler. But if you add a = before each { it will become ordinary and perfectly legal C++98 declaration (and C declaration as well).

There's no problem in using several declarators in one declaration, even if you mix pointer and array declarators. You can add function declarators into that mix, if you wish. The only restriction is that you can't embed function definitions in there.

like image 52
AnT Avatar answered May 17 '23 23:05

AnT