C++ 64 位机器上的 sizeof(int) 应该是多少?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10197242/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 13:44:15  来源:igfitidea点击:

What should be the sizeof(int) on a 64-bit machine?

c++csizeof

提问by Sangeeth Saravanaraj

Possible Duplicate:
size of int, long, etc
Does the size of an int depend on the compiler and/or processor?
What decides the sizeof an integer?

可能的重复:
int、long 等
的大小 int 的大小是否取决于编译器和/或处理器?
什么决定整数的大小?

I'm using a 64-bitmachine.

我在用64-bit机器。

$ uname -m
x86_64
$ file /usr/bin/file
/usr/bin/file: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.32, stripped
$ 

When I ran the following program, I got the sizeof(int)as 4-bytes.

当我运行以下程序时,我得到了sizeof(int)as 4-bytes

#include <stdio.h>

int main(void)
{
    printf("sizeof(int) = %d bytes\n", (int) sizeof(int));

    return 0;
}

If I'm running a 16-, 32-and 64-bit machine, then doesn't it mean that the size of an integeris 16-, 32-and 64-bit respectively?

如果我正在运行16-,32-64-bit 机器,那么这是否意味着 an 的大小分别integer16-,32-64-bit ?

In my machine, I found the WORD_BITis 32. Shouldn't it be 64on a 64-bitmachine?

在我的机器中,我找到了WORD_BITis 32。不应该6464-bit机器上吗?

$ getconf WORD_BIT
32
$ 

And, shouldn't the sizeof(int)be 64-bits(8 bytes) in the above case?

而且,在上述情况下不应该sizeof(int)64-bits( 8 bytes) 吗?

采纳答案by Scott Hunter

Doesn't have to be; "64-bit machine" can mean many things, but typically means that the CPU has registers that big. The sizeof a type is determined by the compiler, which doesn't have to have anything to do with the actual hardware (though it typically does); in fact, different compilers on the same machine can have different values for these.

不一定是;“64 位机器”可能意味着很多东西,但通常意味着 CPU 有那么大的寄存器。类型的大小由编译器决定,它与实际硬件没有任何关系(尽管它通常有);事实上,同一台机器上的不同编译器可以为这些设置不同的值。

回答by Eugene

Size of a pointer should be 8 byte on any 64-bit C/C++ compiler, but not necessarily size of int.

在任何 64 位 C/C++ 编译器上,指针的大小应该是 8 字节,但不一定是 int 的大小。

回答by Dani

Not really. for backward compatibility it is 32 bits.
If you want 64 bits you have long, size_tor int64_t

并不真地。为了向后兼容,它是 32 位。
如果你想要 64 位longsize_t或者int64_t

回答by juanchopanza

In C++, the size of intisn't specified explicitly. It just tells you that it must be at least the size of short int, which must be at least as large as signed char. The size of charin bits isn't specified explicitly either, although sizeof(char) is defined to be 1. If you want a 64 bit int, C++11 specifies long longto be at least 64 bits.

在 C++ 中,int没有明确指定的大小。它只是告诉您它必须至少是 的大小short int,而它必须至少与 一样大signed charcharin 位的大小也没有明确指定,尽管 sizeof(char) 被定义为 1。如果你想要一个 64 位的 int,C++11 指定long long至少为 64 位。