C++ Expression Must Have A Constant Value “? Array Definition

static const int size = 10;void foo() {..int array;..}However, I get the compile error: “expression must have a constant value”, even though size is a constant. I can use the macro

#define SIZE (10)But I am wondering why size marked const causes compilation error.

You are watching: C++ expression must have a constant value

*

*

In C language keyword const has nothing to do with constants. In C language, by definition the term “constant” refers to literal values and enum constants. This is what you have to use if you really need a constant: either use a literal value (define a macro to give your constant a name), or use a enum constant.

(Read here for more details: Shall I prefer constants over defines?)

Also, in C99 and later versions of the language it possible to use non-constant values as array sizes for local arrays. That means that your code should compile in modern C even though your size is not a constant. But you are apparently using an older compiler, so in your case

#define SIZE 10is the right way to go.

*

*

The answer is in another brianowens.tv question, HERE

it”s because In C objects declared with the const modifier aren”t true constants. A better name for const would probably be readonly – what it really means is that the compiler won”t let you change it. And you need true constants to initialize objects with static storage (I suspect regs_to_read is global).

See more: 24 Hour Emergency Eye Care Services, Conditions Requiring Urgent Eye Care

*

if you are on C99 your IDE compiler option may have a thing called variable-length array (VLA) enable it and you won”t get compile error, efficiently without stressing your code though is with MALLOC or CALLOC.

static const int size = 10;

void foo() { int* array; array = (int *)malloc(size * sizeof(int));}
Thanks for contributing an answer to Stack Overflow!

Please be sure to answer the question. Provide details and share your research!

But avoid

Asking for help, clarification, or responding to other answers.Making statements based on opinion; back them up with references or personal experience.

See more: The Term &Quot;Lower Relative Cost&Quot; Is Synonomous With The Concept Of

To learn more, see our tips on writing great answers.

Post Your Answer Discard

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev2021.11.2.40623

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Published

Leave a comment

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