本文介绍了十六进制长整数文字“L"的C解释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据自动转换,C 编译器如何解释表示长整数文字的L"?以下代码在 32 位平台(32 位长,64 位长)上运行时,似乎将表达式(0xffffffffL)"转换为 64 位整数 4294967295,而不是 32 位 -1.

How does a C compiler interpret the "L" which denotes a long integer literal, in light of automatic conversion? The following code, when run on a 32-bit platform (32-bit long, 64-bit long long), seems to cast the expression "(0xffffffffL)" into the 64-bit integer 4294967295, not 32-bit -1.

示例代码:

#include <stdio.h>

int main(void)
{
  long long x = 10;
  long long y = (0xffffffffL);
  long long z = (long)(0xffffffffL);

  printf("long long x == %lld
", x);
  printf("long long y == %lld
", y);
  printf("long long z == %lld
", z);

  printf("0xffffffffL == %ld
", 0xffffffffL);

  if (x > (long)(0xffffffffL))
    printf("x > (long)(0xffffffffL)
");
  else
    printf("x <= (long)(0xffffffffL)
");

  if (x > (0xffffffffL))
    printf("x > (0xffffffffL)
");
  else
    printf("x <= (0xffffffffL)
");
  return 0;
}

输出(在 32 位 Debian 上使用 GCC 4.5.3 编译):

Output (compiled with GCC 4.5.3 on a 32-bit Debian):

long long x == 10
long long y == 4294967295
long long z == -1
0xffffffffL == -1
x > (long)(0xffffffffL)
x <= (0xffffffffL)

推荐答案

它是一个十六进制文字,所以它的类型可以是无符号的.它适合 unsigned long,所以这就是它得到的类型.见标准6.4.4.1节:

It's a hexadecimal literal, so its type can be unsigned. It fits in unsigned long, so that's the type it gets. See section 6.4.4.1 of the standard:

整数常量的类型是其值可以在其中的对应列表中的第一个被代表.

带有后缀 L 的十六进制文字列表是

where the list for hexadecimal literals with a suffix L is

  1. unsigned long
  2. long long
  3. unsigned long long

由于它不适合 32 位有符号 long,而是适合无符号 32 位 unsigned long,所以它变成了.

Since it doesn't fit in a 32-bit signed long, but an unsigned 32-bit unsigned long, that's what it becomes.

这篇关于十六进制长整数文字“L"的C解释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 00:17