-1

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

OS: linuxmint 32-bit

Compiler: gcc & g++

I have try this code:

#include <stdio.h>

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

and I compile it with gcc , the result is 4, and I change to g++, and it is 1

then I use: sizeof(char), and the result is 1

I use: char s = 'a'; printf('%d\n', sizeof(s));

and the result is 1

but I search in the Internet, and some people said that they get the result of 1 or 2.

So why there are so many different result?

Community
  • 1
  • 1
Tanky Woo
  • 4,906
  • 9
  • 44
  • 75
  • 1
    The type of character constants like 'a' in C is int. In C++, it is char. – Ambroz Bizjak Aug 25 '12 at 16:03
  • 1
    Besides not having search the site for a similar question, you also should take care of `printf`. `%d` is never the right format for printing a value of type `size_t` since this is an unsigned type and in addition may have a width that differs from `int`. – Jens Gustedt Aug 25 '12 at 16:16
  • @JensGustedt: The format for `size_t` is `"zu"` (assuming your implementation has caught up to the late 20th century). – Keith Thompson Aug 25 '12 at 17:15
  • @KeithThompson, `%zu` is only valid for C99. This is a question about the intersection of C and C++. Has C++ adopted this, too? – Jens Gustedt Aug 25 '12 at 18:22
  • @JensGustedt: The ISO C11 standard includes the C99 library by reference, so yes, C++ has adopted `"%zu"`. For pre-1999 C or pre-2011 C++, you can use `printf("%lu", (unsigned long)s)`, or `printf("%d", (int)s)` is ok if you know the value isn't too big. – Keith Thompson Aug 25 '12 at 18:47
  • @KeithThompson, you mean ISO C11++? Good to know that this will be fixed as soon as all compilers/libraries comply to C11++. So for the time being if you are programming for the intersection of C/C++ you'd have to use the `%lu` plus cast variant. – Jens Gustedt Aug 25 '12 at 18:52
  • @JensGustedt: I meant ISO C++11 (not "C11++"). – Keith Thompson Aug 25 '12 at 19:51

3 Answers3

1

Character constants are represented as int in C. When you are specifying char type, it's only 1 byte.

Qiau
  • 5,976
  • 3
  • 29
  • 40
1

Character literals like 'a' have type int in C89 which is the default standard used by gcc. In C++ it is important for overloading that characters and strings have types char and char* respectively (think about std::cout << 'a'). Since sizeof(int) == 4 and sizeof(char) == 1 on x86 and x64_86 you get the results you describe.

bitmask
  • 32,434
  • 14
  • 99
  • 159
1

sizeof(char) is always 1, both in C and C++. In C, the type of 'c' is int, so sizeof('c') is the same as sizeof(int). In C++, the type of 'c' is char, so sizeof('c') is the same as sizeof(char), i.e., 1.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165