gpt4 book ai didi

c - int 是 4 个字节,但仍然可以存储在 char 中,为什么没有溢出

转载 作者:太空狗 更新时间:2023-10-29 16:38:12 25 4
gpt4 key购买 nike

检查这个程序

#include<stdio.h>

int main (){

char c='a';
printf("%d %d", sizeof(c),sizeof('a'));
}

输出是1 4
我知道当我们写一个语句时 char c='a';

那怎么会在 1 个字节的空间(char c)中存储一些 4 个字节的东西(ASCII 码),为什么没有溢出等等。

最佳答案

首先,根据 ANSI/IEC 9899:1999(E) §6.4.4.4:

 10. An integer character constant has type int. The value of an integer character constant containing a single character that maps to a single-byte execution character is the numerical value of the representation of the mapped character interpreted as an integer. [...]

§6.5.3.4:

 2. The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. The size is determined from the type of the operand. [...]

 3. When applied to an operand that has type char, unsigned char, or signed char, (or a qualified version thereof) the result is 1. [...]

如您所见,由于字符常量的类型是 int,对于 sizeof('a') 我们得到 sizeof(int),在你的平台上是 4。然而,对于 sizeof(c),我们得到一个 char 的大小,它被定义为 1。

那么为什么我们可以将'a'赋值给char呢?

§6.5.16.1:

 2. In simple assignment (=), the value of the right operand is converted to the type of the assignment expression and replaces the value stored in the object designated by the left operand.

因此,'a'int 被隐式转换为 char。那里也有一个示例,明确显示 int 可以隐式转换为 char

关于c - int 是 4 个字节,但仍然可以存储在 char 中,为什么没有溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6400758/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com