Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

size of char type in C [duplicate]

Tags:

c

char

sizeof

Possible Duplicate:
Why are C character literals ints instead of chars?

folks,

I tried to print out the size of char in C. With the following code, I got the result output as

int, 4
char, 1
char?, 4

Why is the last one not the same as the 2nd one? Thanks.

#include <stdio.h>

main()
{
    int a = 2;
    char b = '2';
    printf("int, %d\n",sizeof(a));
    printf("char, %d\n",sizeof(b));
    printf("char?, %d\n",sizeof('a'));
}
like image 514
nos Avatar asked Mar 03 '12 19:03

nos


People also ask

What is the size of char type in C?

Char Size. The size of both unsigned and signed char is 1 byte always, irrespective of what compiler we use. Here, a signed character is capable of holding negative values. Thus, the defined range here is -128 to +127.

Is char * and int * the same size?

While their size is the same in practice, their alignment requirements are not. If you are doing "kernel coding", that already limits the number of platforms the code can run on. Check with the OS spec what is supported.

Is a char always 1 byte?

Is a char always 1 byte? Yes, in C a char is by definition 1 byte in size. But a byte is not necessarily 8 bits. The number of bits in a byte, or in a char, is specified by the value of the CHAR_BIT macro, defined in <limits.


1 Answers

In C, a character constant like 'a' has type int.

This is different from C++ and Java, where a character constant like 'a' has type char,

like image 178
rob mayoff Avatar answered Sep 28 '22 07:09

rob mayoff