当前位置:网站首页>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

原网站

版权声明
本文为[Luo Hanxiang]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207071619172372.html