Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can we initiate an array literal with variables in C?

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;
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 ) );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading