1

Possible Duplicate:
Size of character ('a') in C/C++

#include <stdio.h>

int main()                
{  
    printf("%d" , sizeof('a'));  
    return 0;  
}

#include <iostream>
using namespace std;     

int main(){  
  cout << sizeof('a');  
  return 0;  
}

For C, it gives 4 as answer whereas for C++ it gives 1 ? My question is why the languages interpret the character constant differently ?

Community
  • 1
  • 1
Pritpal
  • 571
  • 1
  • 6
  • 11
  • 1
    Something interesting (though perhaps not very useful) is you can legally refer to something like 'abcd' (single quotes rather than double)... it doesn't define a char or a string of chars, it defines an int whose value is based on the ascii values of each char strung together. – mah Jun 24 '11 at 18:51
  • Probably and ansi vs. unicode thing, but thats a guess – Conrad Frix Jun 24 '11 at 18:51
  • The rules I'm familiar with are the exact opposite (`sizeof('a')` is 4 in C and 1 in C++). – Max Lybbert Jun 24 '11 at 18:54
  • This question has already been answered [before](http://stackoverflow.com/questions/2172943/size-of-character-a-in-c-c); use the search before asking a question! :) – TkTech Jun 24 '11 at 18:56
  • … Hmm, clicking "ask question" and pasting the text of this there instantly shows that as the first "similar question." No need to click search at all. – Potatoswatter Jun 24 '11 at 18:57
  • Another good thread to look at is this : [sizeof taking two arguments](http://stackoverflow.com/questions/6331588/sizeof-taking-two-arguments) – Nawaz Jun 24 '11 at 19:00
  • new to the site....don't know its features yet – Pritpal Jun 24 '11 at 19:01
  • @mah: It was useful in the old days when apple did company ids as 4 characters (you had to register with apple). Your company ID (4 char) was then encoded as an int int resource part of the application. `companyId = 'appl';` This way it was easy to covert the int ID into a human readable ID any you could guess the company from the ID without looking it up in a big DB. – Martin York Jun 24 '11 at 20:05

2 Answers2

4

Actually sizeof('a') == sizeof(int) in C (so you should get 4). I'm not entirely sure about C++ but I believe sizeof('a') == sizeof(char).

The C part is explained in the C FAQ.

Perhaps surprisingly, character constants in C are of type int, so sizeof('a') is sizeof(int) (though this is another area where C++ differs)

cnicutar
  • 178,505
  • 25
  • 365
  • 392
0

You have managed to find one of the few places where the C and C++ standards differ significantly. They are different answers because the specs say they must be.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622