在C.考虑以下项目
null
// 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; } |
输出:
2 4 6
上面的示例是复合文字的示例。复合文字是在 C的C99标准 .复合文字功能允许我们使用给定的初始化值列表创建未命名对象。在上面的示例中,创建了一个没有任何名称的数组。数组第一个元素的地址被分配给指针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 <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; } |
输出:
2, 3
本文由 希瓦姆·古普塔 .如果你喜欢GeekSforgek,并且想贡献自己的力量,你也可以写一篇文章,并将文章邮寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。
如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END