在 C 中,为什么 sizeof(char) 为 1,而 'a' 是 int? [英] In C, why is sizeof(char) 1, when 'a' is an int?

查看:32
本文介绍了在 C 中,为什么 sizeof(char) 为 1,而 'a' 是 int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试过了

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

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

并得到 1, 4 作为输出.如果一个字符的大小是 1,为什么 'c' 给我 4?我想这是因为它是一个整数.因此,当我执行 char ch = 'c'; 时,当它被分配给 char 变量时,是否存在从 4 字节值到 1 字节值的隐式转换?

and got 1, 4 as output. If size of a character is one, why does 'c' give me 4? I guess it's because it's an integer. So when I do char ch = 'c'; is there an implicit conversion happening, under the hood, from that 4 byte value to a 1 byte value when it's assigned to the char variable?

推荐答案

在 C 中,'a' 是一个整数常量(!?!),所以 4 对你的架构是正确的.它被隐式转换为 char 以进行赋值.根据定义,sizeof(char) 始终为 1.标准没有说明单位 1 是什么,但通常是字节.

In C 'a' is an integer constant (!?!), so 4 is correct for your architecture. It is implicitly converted to char for the assignment. sizeof(char) is always 1 by definition. The standard doesn't say what units 1 is, but it is often bytes.

这篇关于在 C 中,为什么 sizeof(char) 为 1,而 'a' 是 int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆