user2421350
user2421350

Reputation: 157

error with C const string declaration

const char* const back_slash = "\\";
const char* const open_braces ="[";

const char* const array[][2] = {

   {
     back_slash,
    open_braces,

    },
};

In this case i am getting

error: initializer element is not constant

Can you please help?

Upvotes: 1

Views: 215

Answers (4)

user1666959
user1666959

Reputation: 1855

You tried to be too pedantic: C doesn't have real compile time const declarations (with types). One way, to do get the const array part to compile is to declare backslash and open bracket (bracket '[', brace '{') with a #define, unless of course you need them somewhere else. Note about const declarations: one would expect that after 'const int i = 5', i could be used in the code freely and would not appear in the object file. It does, and this can bite you on a small embedded system.

Upvotes: 0

Jens Gustedt
Jens Gustedt

Reputation: 78993

These are const-qualified variables for C, so just variables and not constants in the context of initialization. Use defines to name such literals:

#define back_slash "\\"
#define open_braces "["

Upvotes: 0

Sadique
Sadique

Reputation: 22841

In section 6.7.8/4:

All the expressions in an initializer for an object that has static storage duration shall be constant expressions or string literals.

In the C language, the term "constant" refers to literal constants (like 1, 'a', "[" and so on). back_slash and open_braces are not compile-time constants.

Upvotes: 3

user339222
user339222

Reputation:

An array initializer needs to be a comma-separated list of constant expressions; you are using variables.

Upvotes: 0

Related Questions