unsigned char range

The range for unsigned char is 0 to 255.
Then why output for below program exceed to 255?

1
2
3
4
5
6
7
8
9
10
int main()
{
    printf("Hello World");
    unsigned char s = 150;
    
    for(int i=0;i<s*2;i++)
        printf("%d \n",i);
        
    return 0;
}


Output:
0
2
3
.
.
.
299
1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <typeinfo>
using namespace std;

int main() {
	unsigned char s = 150;
	cout << s*2 << '\n';
	auto x = s*2;
	cout <<  typeid(x).name() << '\n';
}


s*2 is an int, which goes up to a lot more than 255.

Multiplying unsigned char by int gives you an int.
Last edited on
Yes I got it.
Thanks Repeater for reply.
Topic archived. No new replies allowed.