考虑下面的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
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;
}
输出:
2 4 6
上面的示例是复合字面量的示例。复合字面量是在C99标准的C语言中引入的。复合字面量功能使我们可以使用给定的初始化值列表来创建未命名的对象。在上面的示例中,创建了一个没有任何名称的数组。数组的第一个元素的地址分配给指针p。
有什么用?
复合字面量主要用于结构,在将结构变量传递给函数时特别有用。我们可以传递结构对象而不定义它
例如,考虑下面的代码。
// 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
// 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;
}
输出:
2, 3
想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。