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

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

问题描述

在C ++中, sizeof('a')== sizeof(char)== 1 。这是直观的,因为'a'是字符文字, sizeof(char)== 1



在C中, sizeof('a')== sizeof(int)。也就是说,看来C字符文字实际上是整数。有人知道为什么吗?

解决方案

关于相同主题


更具体地说,整数促销。在K& RC中,实际上是(?)
不可能使用字符值,而不是将其提升为int first,
使得字符常数int在第一
有和仍然是多字符常量,如'abcd'或者
许多将适合int。



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.

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.

解决方案

discussion on same subject

"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字符文字ints而不是chars?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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