当前位置:网站首页>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
边栏推荐
- socket编程之常用api介绍与socket、select、poll、epoll高并发服务器模型代码实现
- 万字保姆级长文——Linkedin元数据管理平台Datahub离线安装指南
- Tips for short-term operation of spot silver that cannot be ignored
- 卖空、加印、保库存,东方甄选居然一个月在抖音卖了266万单书
- 备份阿里云实例-oss-browser
- [PaddleSeg源码阅读] PaddleSeg Validation 中添加 Boundary IoU的计算(1)——val.py文件细节提示
- 3分钟学会制作动态折线图!
- 通过 Play Integrity API 的 nonce 字段提高应用安全性
- 【蓝桥杯集训100题】scratch从小到大排序 蓝桥杯scratch比赛专项预测编程题 集训模拟练习题第17题
- pip相关命令
猜你喜欢
Win11C盘满了怎么清理?Win11清理C盘的方法
简单几步教你如何看k线图图解
Chapter 3 business function development (to remember account and password)
备份阿里云实例-oss-browser
用存储过程、定时器、触发器来解决数据分析问题
Do you really understand sticky bag and half bag? 3 minutes to understand it
[论文分享] Where’s Crypto?
五种网络IO模型
Easy to understand [linear regression of machine learning]
Interviewer: why is the page too laggy and how to solve it? [test interview question sharing]
随机推荐
TaffyDB开源的JS数据库
Native JS verification code
Introduction to OTA technology of Internet of things
Using stored procedures, timers, triggers to solve data analysis problems
Hash, bitmap and bloom filter for mass data De duplication
nest.js入门之 database
【demo】循环队列及条件锁实现goroutine间的通信
Five simple ways to troubleshoot with Stace
socket编程之常用api介绍与socket、select、poll、epoll高并发服务器模型代码实现
Slider plug-in for swiper left and right switching
元宇宙带来的创意性改变
[trusted computing] Lesson 12: TPM authorization and conversation
现货白银分析中的一些要点
云景网络科技面试题【杭州多测师】【杭州多测师_王sir】
[principle and technology of network attack and Defense] Chapter 6: Trojan horse
Afghan interim government security forces launched military operations against a hideout of the extremist organization "Islamic state"
Tips for this week 140: constants: safety idioms
go语言的字符串类型、常量类型和容器类型
[principles and technologies of network attack and Defense] Chapter 3: network reconnaissance technology
回归测试的分类