get weird result

this from documentation i changed the int data type to char to save 3 bytes
but when i try to run this program i get strange charcter instead of value

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  // operating with variables

#include <iostream>
using namespace std;

int main ()
{
  // declaring variables:
  char a, b;
  char result;

  // process:
  a = 5;
  b = 2;
  a = a + 1;
  result = a - b;

  // print out the result:
  cout << result;

  // terminate the program:
  return 0;
}
result is of type character so it prints as a character.
Also there is chance that character variable will still take 4-8 bytes in memory (to speedup access time)

use #include <cstdint> and int8_t type
or std::cout << static_cast<int>(result); //Will take another 4 bytes in memory

char = small integer too isnt it? so why i get this char instead of small integer?
Because if the type passed to cout is char, instead of the number the corresponding ascii character is printed. Here's a ascii table: http://www.asciitable.com/
Last edited on
char is a character. It is of integral type, but it is not an integer. it is a character and will be output like one.
1
2
3
char x = 100;
char y = 'd';//Ascii code for d is 100
std::cout << x << ' ' << y; //Will outpur "d d" 


In C++ char is required to be small. But there is no rules about aligment of char. So char x, y; can translate into one byte of data, three bytes of pasdding, one byte of data, three byts of padding.

If you want fixed-width integral type: http://en.cppreference.com/w/cpp/types/integer
I suggest using int_least8_t Note that operation with anything aside int will likely be slower, as int usually thranslates into native CPU register size.
if you want to print the value of a character, you can try to cast it to int:

cout << static_cast<int> (result) ;
So somebody need to fix the documentation

Name Description Size* Range*
char Character or small integer. 1byte signed: -128 to 127
unsigned: 0 to 255



An exception to this general rule is the char type, which exists by itself and is considered a different fundamental data type from signed char and unsigned char, thought to store characters. You should use either signed or unsigned if you intend to store numerical values in a char-sized variable.


It have internal representation as integer. It stores numerical representation of character values and outputting them as characters. It was created to work primarily with text and you cannot output underlying integer without some tricks. You still can use it in comparsion, calculation and everything else you can use int in. But it should not be used to store numbers with inclusion fixed-width integers in C++11.
Topic archived. No new replies allowed.