2

Sorry about the beginners question, but I've written this code:

#include <stdio.h>

    int main()
    {
        int y = 's';
        printf("%c\n", y);
        return 0;
    }

The compiler (Visual Studio 2012) does not warn me about possibility data-loss (like from int to float).
I didn't find an answer (or didn't search correctly) in Google.
I wonder if this because int's storage in memory is 4 and it can hold 1 memory storage as char.
I am not sure about this.

Thanks in advance.

rolory
  • 362
  • 1
  • 2
  • 15
  • 3
    A character is really represented by an integer (look at ASCII representation). Also, char is 8-bit and an int is larger (dependent on platform and not specified as a certain size). – bblincoe Apr 08 '14 at 14:39
  • A `char` is always 1 octet is size, and an `int` is always bigger (actual size depends on different factors, but always bigger). – AntonH Apr 08 '14 at 14:39
  • In C, literal characters have type `int`: `'#'` <== a value with `int` type. – pmg Apr 08 '14 at 15:12

4 Answers4

6

Yes, that's fine. Characters are simply small integers, so of course the smaller value fits in the larger int variable, there's nothing to warn about.

Many standard C functions use int to transport single characters, since they then also get the possibility to express EOF (which is not a character).

unwind
  • 391,730
  • 64
  • 469
  • 606
1

In C, all characters are stored in and dealt with as integers according to the ASCII standard. This allows for functions such as strcmp() etc.

Scy
  • 245
  • 1
  • 12
1

A char is just an 8-bit integer.
An int is a larger integer (on MSVC 32-bit builds it should be 4 bytes).

's' corresponds to the ASCII code of the lower-case letter 's', i.e. it's the integer number 115.

So, your code is similar to:

int y = 115; // 's'
MikePro
  • 192
  • 1
  • 2
  • 6
  • so I can print an integer with `%c` according to his ASCII value? Assuming y=115, and I write this: `printf("%c\n", num)`, this would print s? – rolory Apr 08 '14 at 15:18
0

Despite appearances there is no char anywhere in your example.

For historical reasons character constants are actually ints so the line

int y = 's';

is actually assigning one int to another.

Furthermore the %c format specifier in printf actually expects to receive an int argument, not a char. This is because the default argument promotions are applied to variadic arguments and therefore any char in a call to printf is promoted to an int before the function is called.

Community
  • 1
  • 1
Nigel Harper
  • 1,270
  • 9
  • 13