为什么“unsigned int64_t”在 C 中会出错?

问题描述 投票:0回答:4

为什么下面的程序会出错?

#include <stdio.h>

int main() 
{
    unsigned int64_t i = 12;
    printf("%lld\n", i);
    return 0;
}

错误:

 In function 'main':
5:19: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'i'
  unsigned int64_t i = 12;
                   ^
5:19: error: 'i' undeclared (first use in this function)
5:19: note: each undeclared identifier is reported only once for each function it appears in

但是,如果我删除 unsigned 关键字,它就可以正常工作。所以, 为什么

unsigned int64_t i
给出错误?

c gcc unsigned int64
4个回答
18
投票

您无法对类型

unsigned
应用
int64_t
修饰符。它仅适用于
char
short
int
long
long long

您可能想使用

uint64_t
,它是
int64_t
的无符号对应项。

另请注意,

int64_t
等人。在标头
stdint.h
中定义,如果您想使用这些类型,则应包含该标头。


5
投票

int64_t
不是某种内置类型。尝试添加
#include <stdint.h>
来定义此类类型;然后使用
uint64_t
这意味着你似乎想要什么。


2
投票

int64_t
是一个 typedef 名称。 N1570 §7.20.1.1 p1:

typedef 名称 intN_t 指定宽度为 N 的有符号整数类型,无填充 位和二进制补码表示。因此,int8_t表示这样一个有符号的 宽度恰好为 8 位的整数类型。

标准在 §6.7.2 p2 中列出了哪些组合是合法的:

  • 字符
  • 签名字符
  • 无符号字符
  • 短整型、带符号短整型、短整型或带符号短整型
  • 无符号短整型,或无符号短整型
  • int、有符号或有符号 int
  • 无符号,或无符号整数
  • long、signed long、long int 或signed long int
  • unsigned long,或unsigned long int
  • long long、signed long long、long long int,或者 有符号长长整型
  • unsigned long long,或 unsigned long long int

...

  • typedef 名称

与问题无关的类型已从列表中删除。

注意如何不能将 typedef 名称与

unsigned
混合使用。


要使用无符号64位类型,您需要:

  • 使用

    uint64_t
    (注意前导
    u
    ),不带
    unsigned
    说明符。

    uint64_t i = 12;
    
  • 在定义

    stdint.h
    的位置包含
    inttypes.h
    (或
    uint64_t
    )。

  • 要打印

    uint64_t
    ,您需要包含
    inttypes.h
    并使用
    PRIu64
    :

    printf("%" PRIu64 "\n", i);
    

    您还可以或强制转换为 64 位或更多位的

    unsigned long long
    。然而,当不是绝对必要时,最好避免强制转换,因此您应该更喜欢
    PRIu64
    方法。

    printf("%llu\n", (unsigned long long)i);
    

0
投票

typedef
int64_t
类似于:

typedef signed long long int int64_t;

所以,

unsigned int64_t i;
变成这样:

unsigned signed long long int i;  

这显然是一个编译器错误。

所以,请使用

int64_t
而不是
unsigned int64_t

© www.soinside.com 2019 - 2024. All rights reserved.