当前位置:网站首页>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
边栏推荐
- Ansible learning summary (9) -- ansible loop, condition judgment, trigger, processing failure and other task control use summary
- 性能测试过程和计划
- zdog. JS rocket turn animation JS special effects
- 手机app外卖订餐个人中心页面
- PHP面试题 foreach($arr as &$value)与foreach($arr as $value)的用法
- Learn to make dynamic line chart in 3 minutes!
- Tips for this week 140: constants: safety idioms
- Improve application security through nonce field of play integrity API
- Live broadcast software construction, canvas Text Bold
- 同消费互联网的较为短暂的产业链不同,产业互联网的产业链是相当漫长的
猜你喜欢

Summary of debian10 system problems

讨论 | AR 应用落地前,要做好哪些准备?

Performance test process and plan

你真的理解粘包与半包吗?3分钟搞懂它

DataSimba推出微信小程序,DataNuza接受全场景考验? | StartDT Hackathon

Click on the top of today's headline app to navigate in the middle

Chapter 2 building CRM project development environment (building development environment)

手机app外卖订餐个人中心页面

How to clean when win11 C disk is full? Win11 method of cleaning C disk

Ansible learning summary (9) -- ansible loop, condition judgment, trigger, processing failure and other task control use summary
随机推荐
Automated testing: a practical skill that everyone wants to know about robot framework
Introduction of common API for socket programming and code implementation of socket, select, poll, epoll high concurrency server model
sqlite sql 异常 near “with“: syntax error
Do you really understand sticky bag and half bag? 3 minutes to understand it
Yearning-SQL审核平台
Learn to make dynamic line chart in 3 minutes!
Tips of this week 135: test the contract instead of implementation
[principles and technologies of network attack and Defense] Chapter 5: denial of service attack
idea彻底卸载安装及配置笔记
『HarmonyOS』DevEco的下载安装与开发环境搭建
Easy to understand [linear regression of machine learning]
[PaddleSeg源码阅读] PaddleSeg Validation 中添加 Boundary IoU的计算(1)——val.py文件细节提示
debian10系统问题总结
[principle and technology of network attack and Defense] Chapter 6: Trojan horse
Chapter 3 business function development (safe exit)
Personal best practice demo sharing of enum + validation
[principle and technology of network attack and Defense] Chapter 1: Introduction
Pro2: modify the color of div block
[paddleseg source code reading] add boundary IOU calculation in paddleseg validation (1) -- val.py file details tips
AI 击败了人类,设计了更好的经济机制