tags:

views:

682

answers:

1

What is the size of character in C and C++ ? As far as I know the size of char is 1 byte in both C and 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;
 }

No surprises, both of them gives the output : Size of char : 1

Now we know that characters are represented as 'a','b','c','|',... So I just modified the above codes to these:

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;
 }

Output :

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;
 }

Output :

Size of char : 1
Size of char : 1

So my question is : why the sizeof('a') returns different values in C and C++ ?

+25  A: 

In C, the type of a character constant like 'a' is actually an int, with size of 4. In C++, the type is char, with size of 1. This is one of many small differences between the two languages.

anon
Okay, Can you please specify the standard reference ? :)
nthrgeek
This is pretty much a generic answer given the above code, :P
rmn
In the C++ Standard it's section 2.13.2/1, in C 6.4.4.4, at least in the doc I've got.
anon
+1 (Except that, while the "size of 4" obviously applies to nthrgeek's platform, it doesn't necessarily apply to all platforms.)
sbi
@sbi Of course - I was referring back to his question.
anon
@nthrgeek: I'm too lazy to quote both standards, but the C++ standard has an appendix dedicated to incompatibilities with C. Under Appendix C.1.1, it mentions that "Type of character literal is changed from `int` to `char`, which explains the behavior. :)
jalf
@ jalf : Thanks :)
nthrgeek
It makes sense that C and C++ would have this difference. C++ is much more strongly typed than C.
Omnifarious
@nthrgeek: §6.4.4.4, paragraph 10: "An integer character constant has type int. The value of an integer character constant containing a single character that maps to a single-byte execution character is the numerical value of the representation of the mapped character interpreted as an integer."
Stephen Canon
@Omnifarious: It's especially needed in C++ for overloading: `void foo(int); void foo(char);` That's not an issue in C.
sbi
@nthrgeek: You should not be asking for a standard reference unless you are having an argument about a specific point and you want to understand why the other person has a different opinion. If everybody agrees just accept it. You (as a developer) should be quite intelligent enough to quickly find common answer like this all by yourself.
Martin York