使用"{}"有什么好处?用C语言进行铸造? [英] What are the advantages of using "{}" for casting in C Language?

查看:76
本文介绍了使用"{}"有什么好处?用C语言进行铸造?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解为什么在ProcessHacker代码中使用这种转换样式.

I am trying to understand why use this casting style in ProcessHacker Code.

 RtlSetHeapInformation(
            PhHeapHandle,
            HeapCompatibilityInformation,
            &(ULONG){ HEAP_COMPATIBILITY_LFH }, // HEAP_COMPATIBILITY_LFH = 2UL 
            sizeof(ULONG)
            );

使用"{}"有什么好处?铸造?它可以在C和C ++中使用吗?

What are the advantages of using "{}" for casting? Does it work in C and C++?

&(ULONG){ HEAP_COMPATIBILITY_LFH }, // HEAP_COMPATIBILITY_LFH = 2UL 

推荐答案

&(ULONG){ HEAP_COMPATIBILITY_LFH },

不是演员.这是一个复合文字.它创建一个具有自动存储持续时间的 ULONG 类型的对象,并使用值 HEAP_COMPATIBILITY_LFH 对其进行初始化.然后获取对象的地址.

is not a casting. It is a compound literal. It creates an object of the type ULONG with automatic storage duration and initializes it with the value HEAP_COMPATIBILITY_LFH. Then the address of the object is taken.

这是一个演示程序.

#include <stdio.h>

int main(void) 
{
    unsigned long *p = &( unsigned long ){ 10ul };
    
    printf( "%lu\n", *p );
    
    return 0;
}

程序输出为

10

来自C标准(6.5.2.5复合文字)

From the C Standard (6.5.2.5 Compound literals)

3由带括号的类型名称组成的后缀表达式紧随其后的是一个大括号括起的初始化程序列表文字.它提供了一个未命名的对象,其值由初始化程序列表.

3 A postfix expression that consists of a parenthesized type name followed by a brace enclosed list of initializers is a compound literal. It provides an unnamed object whose value is given by the initializer list.

您可以通过以下方式想象复合文字的定义.

You may imagine the definition of the compound literal the following way.

例如,您可以使用类似括号的列表来初始化标量变量

For example you may initialize a scalar variable using a braced list like

unsigned long x = { 10ul };

但是复合文字没有名称.这样的构造

But a compound literal has no name. So this construction

( unsigned long ){ 10ul }

实际上看起来像

unsigned long unnamed_literal = { 10ul };
     ^                             ^
     |                             | 
( unsigned long )               { 10ul }

请注意,在C ++中,没有像复合文字这样的概念.

Pay attention to that in C++ there is no such a notion as the compound literal.

这篇关于使用"{}"有什么好处?用C语言进行铸造?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆