为什么 C 字符文字是整数而不是字符? [英] Why are C character literals ints instead of chars?

查看:37
本文介绍了为什么 C 字符文字是整数而不是字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C++ 中,sizeof('a') == sizeof(char) == 1.这很直观,因为 'a' 是字符文字,并且 sizeof(char) == 1 由标准定义.

In C++, sizeof('a') == sizeof(char) == 1. This makes intuitive sense, since 'a' is a character literal, and sizeof(char) == 1 as defined by the standard.

然而,在 C 中,sizeof('a') == sizeof(int).也就是说,看起来 C 字符文字实际上是整数.有谁知道为什么?我可以找到很多关于这个 C 怪癖的提及,但没有解释它为什么存在.

In C however, sizeof('a') == sizeof(int). That is, it appears that C character literals are actually integers. Does anyone know why? I can find plenty of mentions of this C quirk but no explanation for why it exists.

推荐答案

讨论 同一主题

更具体地说是积分促销.在 K&R C 中,它实际上是(?)如果不先将字符值提升为 int 就不可能使用它,所以首先使字符常量 int 消除了这一步.过去和现在仍然存在多字符常量,例如 'abcd' 或许多将适合一个整数."

"More specifically the integral promotions. In K&R C it was virtually (?) impossible to use a character value without it being promoted to int first, so making character constant int in the first place eliminated that step. There were and still are multi character constants such as 'abcd' or however many will fit in an int."

这篇关于为什么 C 字符文字是整数而不是字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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