Reputation: 701
I am fairly new to C and during one of my exercises I encountered something I couldn't wrap my head around. When I check the size of an element of tabel (which here is 'b') than I get 4. However if I were to check 'char' than I get 1. How come?
# include <stdio.h>
int main(){
char tabel[10] = {'b','f','r','o','a','u','v','t','o'};
int size_tabel = (sizeof(tabel));
int size_char = (sizeof('b'));
/*edit the above line to sizeof(char) to get 1 instead of 4*/
int length_tabel = size_tabel/size_char;
printf("size_tabel = %i, size_char = %i, lengte_tabel= %i",size_tabel,
size_char,length_tabel);
}
Upvotes: 2
Views: 121
Reputation: 178
sizeof(tabel)
This will return the size of table which is sizeof(char) * 10
sizeof('b')
This will return the sizeof(char) which is one.
Upvotes: 1
Reputation: 145919
An integer character constant, e.g., 'b'
has type int
in C.
From the C Standard:
(c11, 6.4.4.4p10) "An integer character constant has type int. [...] If an integer character constant contains a single character or escape sequence, its value is the one that results when an object with type char whose value is that of the single character or escape sequence is converted to type int."
This is different than C++ where an integer character constant has type char
:
(c++11, 2.14.3) "An ordinary character literal that contains a single c-char has type char, with value equal to the numerical value of the encoding of the c-char in the execution character set."
Upvotes: 3
Reputation: 42598
'b'
is not of type char. 'b'
is a literal and it's type is int.
From C11 Standard Draft (ISO/IEC 9899:201x): 6.4.4.4 Character constants: Description
An integer character constant is a sequence of one or more multibyte characters enclosed in single-quotes, as in 'x'.
Upvotes: 6
Reputation: 513
The 'b'
literal is an int
. And on your current platform, an int
is 4 bytes.
Upvotes: 5