character在c与c++中的区别

先看看如下代码:

In C:

#include <stdio.h>
int main(){
  printf("Size of char : %d\n",sizeof(char));
  return 0;
 }

In C++:

#include <iostream>
int main(){
  std::cout<<"Size of char : "<<sizeof(char)<<"\n";
  return 0;
 }

毫无疑问,输出的是:Size of char :1

我们知道在character代表的是‘a','b','c','|',....这样的东西,所以我只是将上面的代码稍微修改了一下:


In C:

#include <stdio.h>
int main(){
  char a = 'a';
  printf("Size of char : %d\n",sizeof(a));
  printf("Size of char : %d\n",sizeof('a'));
  return 0;
 }

输出:

Size of char : 1
Size of char : 4

In C++:

#include <iostream>
int main(){
  char a = 'a';
  std::cout<<"Size of char : "<<sizeof(a)<<"\n";
  std::cout<<"Size of char : "<<sizeof('a')<<"\n";
  return 0;
 }

输出:

Size of char : 1
Size of char : 1

所以问题来了,为什么sizeof('a')在c和c++中返回的值不同呢?


解释如下:

在c中character类型,如’a'其实是是一个int,而在C++中则是一个char,所以一个是sizeof(int),一个是sizeof(char)。这样就好理解了。

下面是相关英文解释:

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++.

  memset(&i, 'a', sizeof('a'));   // Questionable code 

In practice, this is probably not much of a problem, since character constants are implicitly converted to type int when they appear within expressions in both C and C++.


参考:http://david.tribble.com/text/cdiffs.htm#C99-char-literal(C与C++的区别,很详细)

            http://stackoverflow.com/questions/2172943/size-of-character-a-in-c-c

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值