Consider below program in C.
#include <stdio.h>
int main()
{
int *p = ( int []){2, 4, 6};
printf ( "%d %d %d" , p[0], p[1], p[2]);
return 0;
}
|
Output:
2 4 6
The above example is an example of compound literals. Compound literals were introduced in C99 standard of C. Compound literals feature allows us to create unnamed objects with given list of initialized values. In the above example, an array is created without any name. Address of first element of array is assigned to pointer p.
What is the use of it?
Compound literals are mainly used with structures and are particularly useful when passing structures variables to functions. We can pass a structure object without defining it
For example, consider the below code.
#include <stdio.h>
struct Point
{
int x, y;
};
void printPoint( struct Point p)
{
printf ( "%d, %d" , p.x, p.y);
}
int main()
{
printPoint(( struct Point){2, 3});
return 0;
}
|
Output:
2, 3
Last Updated :
02 Jun, 2017
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...