Simple bit set example

In this piece of code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>

template<typename T>
void print(T t) { std::cout << t << ' '; }

int main() {

	int si = 128; // doesn’t fit into a char
	char c = si; // implicit conversion to char
	unsigned char uc = si;
	signed char sc = si;

	print(si); print(c); print(uc); print(sc); std::cout << '\n';

	si = 128; // doesn’t fit into a signed char
	c = si;
	uc = si;
	sc = si;
	print(si); print(c); print(uc); print(sc); std::cout << '\n';

	system("pause");
	return 0;
}

I expect to get:
128 -128 128 -128
128 -127 129 -127


But I get this one the console:
128 € € €
128 € € €


Why, please?
Last edited on
add a cast to int in print and I get:
C:\c>a
128 -128 128 -128
128 -128 128 -128

so one answer is that it printed as characters, not integers.
but as to the values, not sure what you are trying to see.
Last edited on
Well with VS and Windows, I get a display of:


128 Ç Ç Ç
128 Ç Ç Ç


which is sort of what I expected as c, uc and sc are type char and so are displayed as chars. I also get a bunch of warnings about conversion from int to char and possible loss of data.

If you want the display to be as a number rather than a char, then you need to display as type int/unsigned int as required.

By changing print() to:

1
2
void print(int t) { std::cout << t << ' '; }


I get:


128 -128 128 -128
128 -128 128 -128


With both lines the same as L8 and L15 do the same.
Last edited on
Topic archived. No new replies allowed.