2

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);
    }
BURNS
  • 711
  • 1
  • 9
  • 20
  • Titel and text doesn't match, do they? – harper Jul 15 '14 at 11:35
  • 2
    possible duplicate of [Why are C character literals ints instead of chars?](http://stackoverflow.com/questions/433895/why-are-c-character-literals-ints-instead-of-chars) – Ivaylo Strandjev Jul 15 '14 at 11:36
  • 3
    Is that a duplicate? The mentioned question is in fact the answer, not a duplicate of the question. – Bgie Jul 15 '14 at 11:38

4 Answers4

6

'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'.

Jeffery Thomas
  • 42,202
  • 8
  • 92
  • 117
5

The 'b' literal is an int. And on your current platform, an int is 4 bytes.

Bgie
  • 523
  • 3
  • 10
3

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."

ouah
  • 142,963
  • 15
  • 272
  • 331
1
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.

Jay Godara
  • 178
  • 4
  • 11