Home > Net >  Can we initiate an array literal with variables in C?
Can we initiate an array literal with variables in C?

Time:07-22

I have been searching if we can initiate an array literal with variables but couldn't find it. Bit of context, I want to pass an array literal to a function. Below is what I am trying to do:

int fun(int * a, int num){
    int sum=0;
    for (int i=0; i< num;   i){
        sum = sum   a[i];
    }
    return sum;
}

int main(){

    int a = 3, b =2, c = 1 ;

    int x[3] = {a,b,c}; // Is this legal? It compiles fine on all compilers I tested.
    int p = fun( (int[3]){a,b,c} , 3); // I want to do something like this. pass a literal to the fucntion
    return 0;
}

CodePudding user response:

From the C Standard (6.7.9 Initialization)

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

The string literal defined in this record

int p = fun( (int[3]){a,b,c} , 3);

has automatic storage duration. So you may initialize it with non-constant expressions in particularly using the variables a, b, and c.

Pay attention to that as the function does not change the passed array then the first parameter should have the qualifier const and to avoid overflow it is better to declare the return type as long long int.

Here is a demonstration program.

#include <stdio.h>

long long int fun( const int * a, size_t n )
{
    long long int sum = 0;

    for ( size_t i = 0; i < n;   i )
    {
        sum  = a[i];
    }

    return sum;
}

int main( void )
{
    int a = 3, b = 2, c = 1 ;

    printf( "%lld\n", fun( ( int[] ){a, b, c} , 3 ) );
}

CodePudding user response:

This would not be allowed if the initializer is static, since the value needs to be assigned before the program executes. From C99:

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

Otherwise, each initializer needs to be an "assignment-expression" or, in other words, a valid expression that can be assigned to an object.

So yes, this is legal in C.

CodePudding user response:

Your code (sans the extra x array) compiles just fine with -std=c99 so yes, I'd say it's standard C99 code.

#include <stdio.h>

int fun(int a[], int num) {
  int sum = 0;
  for (int i = 0; i < num;   i) {
    sum = sum   a[i];
  }
  return sum;
}

int main() {
  int a = 3, b = 2, c = 1;
  int p = fun((int[3]){a, b, c}, 3);
  printf("%d", p);
  return 0;
}

CodePudding user response:

Well, yes. The array is being initialized as it should which can be tested by printing it.

The array is also being sent to the function properly as p returns 6. However, do note that you are making a new array to send to the function.

  • Related