Compound Literals in C

3

Consider below program in C.

// Please make sure that you compile this program
// using a C compiler, not a C++ compiler (Save your
// file .cpp). If using online compiler, select "C"
#include <stdio.h>
int main()
{
   // Compound literal (an array is created without
   // any name and address of first element is assigned
   // to p.  This is equivalent to:
   // int arr[] = {2, 4, 6};
   // int *p = arr;
   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.

// Please make sure that you compile this program
// using a C compiler, not a C++ compiler (Save your
// file .cpp). If using online compiler, select "C"
#include <stdio.h>

// Structure to represent a 2D point
struct Point
{
   int x, y;
};

// Utility function to print point
void printPoint(struct Point p)
{
   printf("%d, %d", p.x, p.y);
}

int main()
{
   // Calling printPoint() without creating any temporary
   // Point variable in main()
   printPoint((struct Point){2, 3});

   /*  Without compound literal, above statement would have
       been written as
       struct Point temp = {2, 3};
       printPoint(temp);  */

   return 0;
}

Output:

2, 3

This article is contributed by Shivam Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

Recommended Posts:



3 Average Difficulty : 3/5.0
Based on 2 vote(s)










Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.