1

While working on an arduino project, I created some C++ code that does not compile. After understanding where it stops the essence of it is as follows:

const int xx[]={12,5};

void setup() {
  // put your setup code here, to run once:
const int yy[]={12,5};
}

class aaaa{
  //compilation stops here giving error too many intialiazers for 'const int[0]'
  const int zz[]={12,5};
};


void loop() {
  // put your main code here, to run repeatedly:
}

The question is why it does not compile giving error "too many intialiazers for 'const int[0]'. Should it behave like that ?

2
  • The fact that you are redefining new arrays with the same name and values as a const global array indicates to me that you may be confused about what const int xx[]={12,5}; means. What are you trying to achieve exactly? Commented Aug 27, 2020 at 15:33
  • No it was just an abstract example taken out of my code when I understood where the problem was. Thus I should use static in order to overcome the compiler limitations, or just put the number of elements. What I haven't realized is that the compiler puts the constants inside the structure, something that I don't know if it is needed by the standard or not in that case. Commented Aug 27, 2020 at 17:00

1 Answer 1

1

Your first array declares a global variable, this is allowed to have a size defined by an initialiser.

Your second array is a local variable, again this is allowed to have a size defined by an initialiser.

Your third array is a member of a structure, structure members must have a fixed size so that the structure itself has a fixed size. The size isn't allowed to be deduced from the initialiser.

Clang gives a clearer error message:

error: array bound cannot be deduced from an in-class initializer
Sign up to request clarification or add additional context in comments.

2 Comments

To me it seems that the const inside a class does not take space inside the data of the structure related to the class as it is essentially a field shared among all the instances of the class. So the inability to deduce is just a compiler problem to be corrected, unless I miss something I would like to know.
no, it is not static so it is a member of the class, the const is irrelevant

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.