c - 使用 `union` 在整数和数组之间输入双关语?

标签 c arrays unions type-punning

在整数和整数数组之间进行类型双关是否合法?

具体代码:

#include <nmmintrin.h>
#include <stdint.h>

union   Uint128 {
    __uint128_t uu128;
    uint64_t    uu64[2];
};

static inline   uint_fast8_t    popcnt_u128 (__uint128_t n)
{
    const union Uint128 n_u     = {.uu128 = n};
    const uint_fast8_t  cnt_a   = _mm_popcnt_u64(n_u.uu64[0]);
    const uint_fast8_t  cnt_b   = _mm_popcnt_u64(n_u.uu64[1]);
    const uint_fast8_t  cnt     = cnt_a + cnt_b;

    return  cnt;
}

最佳答案

是的,C 标准明确预见了通过 union 在所有数据类型之间进行类型双关。没有针对阵列的特殊规定会禁止这样做。

关于c - 使用 `union` 在整数和数组之间输入双关语?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55010795/

相关文章:

C - 初始化哈希表

c - fscanf 在文件末尾返回 3 而不是 -1 (EOF)

c - C语言中的指针和数组

c - 将 char 数组分配给 union 数据类型时,我的编译器抛出错误 : "conversion from char* to non-scalar type"

c++,是否可能在不同的头文件中有两个同名的 union

python - 将负 float 转换为无符号整数

c - Strtok 删除分隔符之前的最后一个字符

html - ngFor - 按索引打印数组项

java : passing array of reference?

c# - C# 中联合的奇怪解码行为