0

I was trying to write the code as follows:

In header file: test.h

#define size_aspid 8
 const char replace_aspid[20];
 void print_max_length();

In test.c file:

const char replace_aspid[] = "replace_aspidiii";

int max_size = size_aspid+strlen(replace_aspid);
void print_max_lenght()
{
       printf("Max length is: %d\n",max_size);
}

In main.c file:

  int main()
   {
      print_max_length();
      return 0;
   }

Then the compiler says the following:

warning: initializer element is not a constant expression
#define size_aspid 8
note: in expansion of macro ‘size_aspid’
int max_size       = size_aspid+strlen(replace_aspid);

where i am going wrong. Thanks!!!!!!!!!!!

Abhijatya Singh
  • 642
  • 6
  • 23

2 Answers2

1

The initializer of a variable declared at file scope has to be a constant expression. A function call (in your case strlen) is never a constant expression in C.

You can replace:

int max_size = size_aspid+strlen(replace_aspid);

with

int max_size = size_aspid + (sizeof replace_aspid - 1);

sizeof is an operator and not a function and here is a constant expression.

ouah
  • 142,963
  • 15
  • 272
  • 331
0

Assuming int max_size is defined globally, you may not use functions to initialise it.

strlen(replace_aspid)

is not constant, at least not in the context of C.

To fix this very issue use

(sizeof replace_aspid - 1) /* Thanks to ouah for the -1! :-) */

instead. It evaluates at compile time and with this treated as constant by the compiler.

alk
  • 69,737
  • 10
  • 105
  • 255