"array bound is not an integer constant" when determining the size of an array in a class using an array element const

#ifndef QWERT_H
#define QWERT_H

const int x [] = {1, 2,};
const int z = 3;
#endif


#include <iostream>
#include "qwert.h"
class Class   
{  
    int y [x[0]];  //error:array bound is not an integer constant
    int g [z];     //no problem  
};


int main ()  
{  

    int y [x[0]];      //no problem
    Class a_class;

}

I can’t understand why this is not working. Other people with this problem seem to be trying to dynamically allocate arrays. Any help is greatly appreciated.

+3
source share
3 answers

The main version works because your compiler has an extension that allows the use of variable-length arrays. Access to arrays cannot be a constant expression in C ++ 03, even if the array and index are constant expressions that are the source of the error.

+3
source

x const (, , z), x [0] . .

; , sizeof , ?

+4

The size of the array must be a constant expression. I do not believe that constant elements in an array qualify as such.

Work in the main () version is probably related to the compiler extension.

+1
source

Source: https://habr.com/ru/post/1785263/


All Articles