Ali
Ali

Reputation: 426

C - Set the value of a static variable if unset

I have the following code snippet:

#include<stdio.h>
void read(int a[ ],int n)
{
      static int p=n;
      if(n!=0)
       {
           printf("enter element %d: ",p-n);
           scanf("%d",&a[p-n]);
           read(a,n-1);
        }
}
int main()
{
   int a[10],n;
   printf("enter n: ");
   scanf("%d",&n);
   read(a,n);
}

I keep getting the error: initializer element is not constant. Isn't n constant by the time the function compiles?

Edit: Problem: How to set the value of a static variable(if it isn't set) within a function?

Upvotes: 0

Views: 178

Answers (4)

ddz
ddz

Reputation: 526

It is because you can't initialize a static variable with another variable, only with constant values that can be determined at compile time, such as macros, literals, etc.

Upvotes: 4

Ani Menon
Ani Menon

Reputation: 28199

Edit : Solution is assign p to n only if p is unset

Solution:

#include<stdio.h>
static int p;
void read(int a[ ],int n)
{
    //p=n; //to change n on each call 
    if(!p) p = n; //to change n only if p is unset
      if(n!=0)
       {
           printf("enter element %d: ",p-n);
           scanf("%d",&a[p-n]);
           read(a,n-1);
        }
}
int main()
{
    int a[10],n;
    printf("enter n: ");
    scanf("%d",&n);
    read(a,n);
}

Upvotes: 1

abhiarora
abhiarora

Reputation: 10430

I keep getting the error: initializer element is not constant.

Global and static variables can only be initialized with constant expressions known at compile time.

Isn't n constant by the time the function compiles?

The answer is no. The n stores value received from stdin. Therefore, it receives the value during run-time.

Upvotes: 2

Cyb3rFly3r
Cyb3rFly3r

Reputation: 1341

Most certainly not; how does the compiler know what value is going to be assigned to n at compile time?

Upvotes: 2

Related Questions