-1

In Difference between char and int when declaring character, the accepted answer says that the difference is the size in bits. Although, MicroVirus answer says:

it plays the role of a character in a string, certainly historically. When seen like this, the value of a char maps to a specified character, for instance via the ASCII encoding, but it can also be used with multi-byte encodings (one or more chars together map to one character).

Based on those answers: In the code below, why is the output not the same (since it's just a difference in bits)? What is the mechanism that makes each type print a different "character"?

#include <iostream>

int main() {
    int a = 65;
    char b = 65;
    std::cout << a << std::endl;
    std::cout << b << std::endl;
    //output :
    //65
    //A
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 4
    They call different overloads of `operator<<` – UnholySheep Oct 13 '21 at 20:51
  • 1
    Because there's a different implementation for those different types how these are represented as text. If you want to see the `char` value as a number, you can do as described [here](https://stackoverflow.com/questions/19562103/uint8-t-cant-be-printed-with-cout/19562163#19562163). – πάντα ῥεῖ Oct 13 '21 at 20:51
  • 1
    Different types can have difference in what they're intended to mean and how they're handled, beyond just being difference in number of bytes. – TheUndeadFish Oct 13 '21 at 20:53
  • The size of `char` and size of `int` are defined in terms of range. A character type can be 512 bits, as long as it can support the range for `char`. Similarly, an `int` type needs to have a minimum quantity of **bytes** to support the required range; the `int` can be larger than that. – Thomas Matthews Oct 13 '21 at 21:04
  • 1
    If you need *specific* bit widths, you are encouraged to use the `u*_t` types, such as `uint8_t` or `uint32_t`; there are also bit width types for signed integers. – Thomas Matthews Oct 13 '21 at 21:06
  • 1
    *"the accepted answer says that the difference is the size in bits"* vs. *"since it's just a difference in bits"* -- you added a misleading word. The difference is the size, but it's not *just* a difference in size. There is also a difference in semantics (a `char` represents a character, while an `int` represents an integer). Similarly, the word "only" in your title is an added misleading word. – JaMiT Oct 13 '21 at 21:13

1 Answers1

1

A char may be treated as containing a numeric value and when a char is treated such it indeed differs from an int by its size -- it is smaller, typically a byte.

However, int and char are still different types and since C++ is a statically typed language, types matter. A variable's type can affect the behavior of programs, not just a variable's value. In the case in your question the two variables are printed differently because the operator << is overloaded; it treats int and char differently.

jwezorek
  • 8,592
  • 1
  • 29
  • 46