当前位置:网站首页>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
边栏推荐
- Pro2: modify the color of div block
- Introduction de l'API commune de programmation de socket et mise en œuvre de socket, select, Poll et epoll
- USB通信协议深入理解
- Native JS verification code
- idea彻底卸载安装及配置笔记
- 【蓝桥杯集训100题】scratch从小到大排序 蓝桥杯scratch比赛专项预测编程题 集训模拟练习题第17题
- [principle and technology of network attack and Defense] Chapter 7: password attack technology Chapter 8: network monitoring technology
- Tips of this week 141: pay attention to implicit conversion to bool
- In depth understanding of USB communication protocol
- 2022年理财产品的一般收益率是多少?
猜你喜欢
Explain it in simple terms. CNN convolutional neural network
Test for 3 months, successful entry "byte", my interview experience summary
Target detection 1 -- actual operation of Yolo data annotation and script for converting XML to TXT file
Disk storage chain B-tree and b+ tree
Download, installation and development environment construction of "harmonyos" deveco
磁盘存储链式的B树与B+树
In depth understanding of USB communication protocol
Discuss | frankly, why is it difficult to implement industrial AR applications?
『HarmonyOS』DevEco的下载安装与开发环境搭建
你真的理解粘包与半包吗?3分钟搞懂它
随机推荐
Run Yolo v5-5.0 and report an error. If the sppf error cannot be found, solve it
备份阿里云实例-oss-browser
讨论| 坦白局,工业 AR 应用为什么难落地?
Learn to make dynamic line chart in 3 minutes!
[principle and technology of network attack and Defense] Chapter 7: password attack technology Chapter 8: network monitoring technology
Chapter 1 Introduction to CRM core business
[OKR target management] value analysis
Tips for short-term operation of spot silver that cannot be ignored
Deep learning - make your own dataset
2022年理财产品的一般收益率是多少?
Mobile app takeout ordering personal center page
『HarmonyOS』DevEco的下载安装与开发环境搭建
cf:C. Factorials and Powers of Two【dp + 排序 + 选不选板子 + 选若干个数等于已知和的最少数】
[principle and technology of network attack and Defense] Chapter 6: Trojan horse
保证接口数据安全的10种方案
Use seven methods to enhance all the images in a folder
Chapter 2 building CRM project development environment (building development environment)
AI 击败了人类,设计了更好的经济机制
[论文分享] Where’s Crypto?
[network attack and defense principle and technology] Chapter 4: network scanning technology