Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Compound Literals in C
In C, compound literals are a feature introduced in the C99 standard that allows you to create unnamed objects with automatic storage duration. This feature enables you to initialize arrays, structures, and unions directly in expressions without declaring a separate variable.
Syntax
(type_name) { initializer_list }
Example 1: Compound Literal with Structure
Here's how to use compound literals to create an unnamed structure object −
#include <stdio.h>
struct point {
int x;
int y;
};
void display_point(struct point pt) {
printf("(%d,%d)<br>", pt.x, pt.y);
}
int main() {
display_point((struct point) {10, 20});
return 0;
}
(10,20)
Example 2: Compound Literal with Arrays
Compound literals can also be used with arrays −
#include <stdio.h>
void print_array(int arr[], int size) {
for(int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("<br>");
}
int main() {
print_array((int[]){1, 2, 3, 4, 5}, 5);
/* Using compound literal to initialize pointer */
int *ptr = (int[]){10, 20, 30};
printf("First element: %d<br>", ptr[0]);
return 0;
}
1 2 3 4 5 First element: 10
Example 3: Compound Literal with String
Compound literals work with character arrays as well −
#include <stdio.h>
#include <string.h>
int main() {
char *str = (char[]){"Hello World"};
printf("String: %s<br>", str);
printf("Length: %lu<br>", strlen(str));
return 0;
}
String: Hello World Length: 11
Key Points
- Compound literals have automatic storage duration and exist only within the block scope where they are defined.
- They are lvalues, meaning you can take their address and modify their contents.
- The syntax is
(type_name) { initializer_list }. - They are particularly useful for passing temporary objects to functions.
Conclusion
Compound literals in C provide a convenient way to create temporary unnamed objects directly in expressions. They enhance code readability and eliminate the need for creating separate variables for temporary data structures.
Advertisements
