当前位置:网站首页>The highest level of anonymity in C language
The highest level of anonymity in C language
2022-07-07 18:20:00 【Luo Hanxiang】
Link to the original text :C The highest level of anonymity in language
C Have you ever seen in language (int [2]){19,20}
perhaps int (*pt2)[4]
How to use , It may not be easy to understand literally , This is a C99 Knowledge points added later , be known as Compound expression Compound Literals
, Once familiar with the use , You will realize its concise and powerful expression .
What is? ” Compound expression “?
Suppose to bring int The formal parameter function of type passes a value , It can deliver int Variable of type , It can also deliver int Type constant , But it is different for functions with array parameters , You can pass arrays , But passing array constants is not supported , thus C99 Added “ Compound expression ” Usage of ,“ describe (Literals)” It refers to constants other than symbolic constants .
for example 10 It's a kind of int The type of expression ,10.24 It's a kind of double Expression of type ,“lixiaoyao” Is a string type expression, etc —— These are statements about constant values of a single type . spontaneous , For data types with multiple members such as arrays or structures , The expression of constants is called compound expression .
About the compound expression of array
The compound expression of array is similar to that of array initialization list , Type names preceded by parentheses , For example, here is a common array declaration .
int age[2]=[19,20];
Below we create a and age Array the same anonymous array , There are also two int Type values .
(int [2]){19,20}; // Compound expression
Notice to remove the array name in the declaration , Leave the int[2]
It is the type name of compound expression .
Initializing an array with an array name can omit the size of the array , Compound expressions can also omit size , The compiler automatically calculates the current number of elements in the array :
(int []){19,20,21,22,23}// contains 5 Compound expression of elements
Because compound expressions are anonymous , So you can't create it first and then use it , You have to use it at the same time you create it , as follows :
int x;
// correct
x = 100;
int arr[1];
// error
arr = {0};
Generally, we need to define and use :
int *pt1;
pt1=(int[2]){19,20};
Be careful , The literal constants of this compound expression are the same as those created above age The expression quantity of array is exactly the same , The type name of the compound expression also represents the address of the first element , So you can assign it to the point int The pointer to .
As actual parameter
The compound expression is passed as an actual parameter to a function with matching formal parameters .
#include <stdio.h>
int sum(const int age[],int n);
int main () {
int total;
total =sum((int[]){4,4,4,5,5,5},6);
return 0;
}
int sum(const int age[],int n){
int i=0;
for(i=0;i<n;i++){
printf("age is %d\n",age[i]);
}
}
The output is as follows :
Apply to two-dimensional arrays or multi-dimensional arrays
This usage can also be applied to two-dimensional or multi-dimensional arrays , For example, the following demonstrates how to create a two-dimensional int Array and store its address .
int (*pt2)[4];
// Declare a pointer to a two-dimensional array , This array contains 2 Array elements
// Each element contains 4 individual int An array of type values
pt2 = (int [2][4]) {
{1,2,3,4,},{5,6,7,8,}};
For structures
Suppose that struct foo and structure:
struct foo {
int a;
char b[2];
} structure;
This is the use of compound expression construction struct foo An example of :
structure = ((struct foo) {x + y, 'a', 0});
This is equivalent to the following code :
{
struct foo temp = {x + y, 'a', 0};
structure = temp;
}
You can also construct an array , As follows , If all elements of a compound expression are composed of simple constant expressions , You can cast a compound expression to a pointer to its first element , And use in this initialization program , As shown below :
char **foo = (char *[]) { "x", "y", "z" };
Compound representations of scalar types and union types are also allowed , In the following example , Variable i Initialize to value 2, This value is the result of increasing the unnamed object created by the compound representation .
int i = ++(int){1};
As GNU Expand ,GCC It is allowed to initialize objects with static storage duration through compound expression , If the compound representation matches the type of the object , The object is processed as if it were initialized with a list enclosed in parentheses only , The elements of a compound expression must be constants . If the object to be initialized has an array type of unknown size , Then the size is determined by the size of the compound expression .
static struct foo x = (struct foo) {1, 'a', 'b'};
static int y[] = (int []) {1, 2, 3};
static int z[] = (int [3]) {1};
Equivalent to the following :
static struct foo x = {1, 'a', 'b'};
static int y[] = {1, 2, 3};
static int z[] = {1, 0, 0};
C/C++ The difference between
The compound expression looks like a cast of an aggregate initializer list enclosed in parentheses , Its value is the object of the specified type in the cast , It contains the elements specified in the initializer .
Different from the result of forced conversion , Compound expression is left value , however C++ At present, there is no such unknown lvalue in , As an extension ,GCC stay C90 Patterns and C++ Complex expressions are also supported in , but C++ Semantics are different .
stay C in , A compound representation represents an unnamed object with a static or automatic storage duration ; stay C++ in , A compound representation represents a temporary object , The object exists only until its full expression ends .
therefore , Well defined C Code ( The address of the child object expressed in compound ) Can be in C++ Not defined in , therefore g++ The compiler cannot convert temporary arrays to pointers .
for example , If the above array compound expression example appears inside the function , be C++ Chinese vs foo Any subsequent use of will have undefined behavior , Because the lifetime of the array is declared foo And then it's over .
As an optimization ,g++ Compilers sometimes provide a longer lifetime for complex representations of arrays : When an array appears outside a function or has const When qualifying types . If foo The element type of its initializer is char * const
instead of char *
, perhaps foo Is a global variable , Then the array will have a static storage duration .
Reference resources :https://gcc.gnu.org/onlinedocs/gcc/Compound-Literals.html
边栏推荐
- Tips for this week 131: special member functions and ` = Default`
- [OKR target management] value analysis
- [PaddleSeg源码阅读] PaddleSeg Validation 中添加 Boundary IoU的计算(1)——val.py文件细节提示
- 【demo】循环队列及条件锁实现goroutine间的通信
- 带动画的列表选中js特效
- 备份阿里云实例-oss-browser
- 你真的理解粘包与半包吗?3分钟搞懂它
- < code random recording two brushes> linked list
- How to clean when win11 C disk is full? Win11 method of cleaning C disk
- Win11C盘满了怎么清理?Win11清理C盘的方法
猜你喜欢
Target detection 1 -- actual operation of Yolo data annotation and script for converting XML to TXT file
手撕Nacos源码(先撕客户端源码)
回归问题的评价指标和重要知识点总结
debian10系统问题总结
Easy to understand [linear regression of machine learning]
Backup Alibaba cloud instance OSS browser
[deep learning] 3 minutes introduction
Explain it in simple terms. CNN convolutional neural network
Face recognition attendance system based on Baidu flying plasma platform (easydl)
[principle and technology of network attack and Defense] Chapter 6: Trojan horse
随机推荐
<代码随想录二刷>链表
2021年全国平均工资出炉,你达标了吗?
直播软件搭建,canvas文字加粗
Youth experience and career development
Using stored procedures, timers, triggers to solve data analysis problems
Machine vision (1) - Overview
保证接口数据安全的10种方案
磁盘存储链式的B树与B+树
仿今日头条APP顶部点击可居中导航
Download, installation and development environment construction of "harmonyos" deveco
用存储过程、定时器、触发器来解决数据分析问题
简单几步教你如何看k线图图解
小试牛刀之NunJucks模板引擎
Target detection 1 -- actual operation of Yolo data annotation and script for converting XML to TXT file
Mobile app takeout ordering personal center page
[paddleseg source code reading] add boundary IOU calculation in paddleseg validation (1) -- val.py file details tips
“解密”华为机器视觉军团:华为向上,产业向前
手撕Nacos源码(先撕客户端源码)
Do you really understand sticky bag and half bag? 3 minutes to understand it
In depth understanding of USB communication protocol