1

I have a simple program as below:

static const char* DeviceID = (char*)"my id";
int length = strlen(DeviceID);
int main(){

}

and the compiler throw the following error:

initializer element is not constant

I don't know why the compiler can't understand my statement:
strlen's prototype is like the following code:

size_t strlen ( const char * str );
5
  • Because it is outside a function? C doesn't have static constructors; functions can only be called from within functions. Call strlen where you need it. Or are you using C++? (You specify both tags.) Commented Jun 3, 2014 at 9:26
  • 1
    Why did you tag this C++ if you're not using a C++ compiler? Commented Jun 3, 2014 at 9:27
  • Also, in this particular case you don't even need to call an actual function, if you do static const char[] DeviceID = "my id"; you can use sizeof on it. Commented Jun 3, 2014 at 9:28
  • 1
    static const char[] DeviceID = "my id"; Commented Jun 3, 2014 at 9:33
  • 1
    static const char DeviceID[] = "my id"; Commented Jun 3, 2014 at 9:54

2 Answers 2

1

Try sizeof which yields a compile time constant

#define MY_ID "my id"
static const char *DeviceID = MY_ID;  // no cast needed
int length = sizeof MY_ID - 1;        // sizeof also includes the '\0'

int main(void) {
    /* ... */
}
Sign up to request clarification or add additional context in comments.

Comments

1

As far as I know, there is different with C and C++ when you're trying to initailize global variables.

in C, Rvalue of the global initializing statement should be evaluated at compile time.
for instance,

  1. static const char* DeviceID = (char*)"my id"; <-- compiler can evaluate address of "my_id". so, this is valid.

  2. int length = strlen(DeviceID); <-- but this can't be at compiletime. means that, we should run the process in order to know its value.

But, C++ doesn't care about like above. it can initialize global ones at runtime. so if you use C++ compiler instead of, errors'll be disappeared.

Comments

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.