C99 allows us to use compound literal
The feature called compound literal enables us to create unnamed array and structure values
Usually, what we do in C, first we need to declare and, then initialize a variable before we call
As can be seen, from the below example
float b[]={3,0,3,4,1};
float result = calculateSum(b,5);
But, if b isn’t needed for any other purpose then it will be a little annoying right? To create it solely for the purpose of calling calculateSum
On the other hand, with C99 we can avoid this annoyance by using the feature called compound literal which is an unnamed array that is created simply by specifying the element it contains
float result = calculateSum((float[]){3,0,3,4,1},5);// function call
As can be seen, from the above function call calculateSum has a compound literal ((float[]){3,0,3,4,1}) as its first argument
Let’s deconstruct an example
#include <stdio.h>
float calculateSum(float num[], float n);//function prototype declaration
int main() {
float result = calculateSum((float[]){3,0,3,4,1},5);// function call
printf("Result = %.2f", result);
return 0;
}
float calculateSum(float num[], float n)//function declaration
{
float sum = 0.0;
for (int i = 0; i < n; ++i) {
sum += num[i];
}
return sum;
}
Output
result = 11.00
Leave a Reply