Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Storage Size Isn't a Constant...why?

Here's the simple example program

#include <stdio.h>
#include <string.h>

const char *hello_string = "Hello";

int main(void)
{
char *world_string = " World";
static char hello_world[strlen(hello_string)+strlen(world_string)];
strcpy(&hello_world[0], hello_string);
strcat(&hello_world[0], world_string);
printf("%s\n", hello_world);
return 0;
}

The compiler output:

test.c: In function ‘main’:
test.c:9:13: error: storage size of ‘hello_world’ isn’t constant
static char hello_world[strlen(hello_string)+strlen(world_string)];
            ^

I realize the completely useless and unnecessary use of "static" in this case causes the error and with its removal things will compile fine. This is just a simple example to illustrate my question.

What I don't understand is why the storage size is not a constant when the "hello_string" is declared as const char * and its size is not going to change during the course of execution. Is this just a case of the compiler not being smart enough to know that?

like image 692
user2738091 Avatar asked Sep 01 '13 21:09

user2738091


2 Answers

When the compiler complains about storage size not being constant implicitly means compile-time constant, i.e. a value that the compiler can determine at compile-time. The call of strlen obviously would happen at runtime, so the compiler cannot know the size of your array.

Try this:

#include <stdio.h>
#include <string.h>

const char hello_string[] = "Hello";

int main(void)
{
    char world_string[] = " World";
    static char hello_world[sizeof hello_string + sizeof world_string];
    strcpy(&hello_world[0], hello_string);
    strcat(&hello_world[0], world_string);
    printf("%s\n", hello_world);
    return 0;
}
like image 74
Lorenzo Donati -- Codidact.com Avatar answered Sep 17 '22 15:09

Lorenzo Donati -- Codidact.com


strlen is a function. It's return value cannot be calculated at compile time.

like image 42
JeremyP Avatar answered Sep 16 '22 15:09

JeremyP