在C中打印char的大小 [英] Printing the size of char in C

查看:182
本文介绍了在C中打印char的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我打印sizeof('b');在c中它是打印4,但它应该打印1因为b不是整数,它是一个字符

但是当我声明char b时;然后它的ascii值也需要4个字节,然后它的打印1;或者我们可以说在那种情况下ascii值在整数后也不会占用4个字节如何?



我尝试过:



when I am printing sizeof('b'); in c it is printing 4, But it should print 1 because b is not a integer ,it is a char
but when I am declaring char b; then its ascii value will also take 4 byte but then its print 1; or we can say that in that case ascii value will NOT take 4 byte after being an integer also HOW??

What I have tried:

#include<stdio.h>
 int main(){
 printf("the size of b is %d",sizeof('b')); 

 }

推荐答案

使用当前设置进行实验。



声明一个byte,char,short int,int。

现在运行sizeof()。



您的系统可以将字符默认设置为一个字节以外的大小。



从谷歌搜索sizeof(char)in c:



Do an experiment with your current setup.

Declare a byte, char, short int, int.
Now run sizeof() on them.

Your system can have characters default to sizes other than one byte.

from a google search for "sizeof(char) in c":

引用:

它取决于字符是什么以及它是什么编码:8-中的ASCII字符位ASCII编码是8位(1字节),但它可以适合7位。 ISO-8859-1编码中的ISO-8895-1字符是8位(1字节)。 UTF-8编码中的Unicode字符介于8位(1字节)和32位(4字节)之间.Jan 31,2011

It depends what is the character and what encoding it is in: An ASCII character in 8-bit ASCII encoding is 8 bits (1 byte), though it can fit in 7 bits. An ISO-8895-1 character in ISO-8859-1 encoding is 8 bits (1 byte). A Unicode character in UTF-8 encoding is between 8 bits (1 byte) and 32 bits (4 bytes).Jan 31, 2011


这似乎是使用的结果作为参数的文字('a')首先将'a'分配给变量。

This appears to the result of using a literal ('a') as the argument vs assigning 'a' to a variable first.


字符文字

在C中,字符文字(如'a')的类型为int,因此sizeof('a')等于sizeof(int)。

在C ++中,字符文字有键入char,因此sizeof('a')等于sizeof(char)。

这种差异可能导致某些代码中的行为不一致,这些代码被编译为C和C ++。



来源: C和C ++之间的不兼容性:字符文字 [ ^ ]


Character literals
In C, character literals such as 'a' have type int, and thus sizeof('a') is equal to sizeof(int).
In C++, character literals have type char, and thus sizeof('a') is equal to sizeof(char).
This difference can lead to inconsistent behavior in some code that is compiled as both C and C++.

Source: Incompatabilities between C and C++: Character literals[^]


在你的代码中'b'是一个char,但是一个未命名的变量。这是将编译器默认为int。



在编程中,最好尽可能精确因为编译器和链接器可能理解你的代码与你有点不同,并喜欢优化它。我最近(并且再次)获得了体验,即析构函数中的某些代码永远不会被执行,因为优化过程会抛弃它。
In your code the 'b' isnt a char, but an unnamed variable. And this is defaulting the compiler to an int.

In programming it is best to be as precise as possible because compiler and linker may understand your code a little different than you and like to optimize it. I made lately (and again) the experience that some code in destructors is never excuted, because the optimizing process thrown it away.


这篇关于在C中打印char的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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