# multiplying chars

• 11-20-2008
orjanb314
multiplying chars
Code:

``` char test1 = 15; char test2 = 10; char test3 = test1*test2; printf("%d ", test3);```
Why does this code result in printing out -106? Is there any way I can easily make test3 into the correct value of 150, or is it just stupid using chars like this?
• 11-20-2008
matsp
Chars are signed by default [in most compilers] and any value with the highest bit set (that is, a value above 127 in most architectures) will be considered a negative number. In this case, 150 is bigger than 127, so it is treated as a negative number - essentially 150-256 => -106

--
Mats
• 11-20-2008
bbebfe
The value of char in C is (-128 -> 127), or using unsigned char instead of char if you want 150.
• 11-20-2008
matsp
Quote:

Originally Posted by bbebfe
The value of char in C is (-128 -> 127)

This is of course not GUARANTEED (a DEC-10 would perhaps have 4 chars per 36-bit word -> 9 bit per char and a range of -256..255, to give an example), but yes, it's negative because it's above the positive range of the char numbers in this architecture.

--
Mats
• 11-20-2008
orjanb314
Is there such a thing as unsigned char, like with int?
• 11-20-2008
orjanb314
Never mind, took me 30 secs to test it myself, thanks for the answers.
• 11-20-2008
bbebfe
matsp is right， How max and min of a type, there is no definite value within C, It's depends on the C compiler and target system. You can get the max and min value of char by referring the CHAR_MAX and CHAR_MIN macros defined in <limits.h>
Code:

`printf("max=&#37;d, min=%d\n", CHAR_MAX, CHAR_MIN);`
• 11-20-2008
Salem
> Chars are signed by default
Without qualification, whether a 'char' is signed or unsigned is implementation-specific.

gcc (for example) has a flag to change the behaviour, should it happen to matter.
• 11-20-2008
matsp
Quote:

Originally Posted by Salem
> Chars are signed by default
Without qualification, whether a 'char' is signed or unsigned is implementation-specific.

gcc (for example) has a flag to change the behaviour, should it happen to matter.

Yes, that's why I put "[in most compilers]". And I know a few other compilers also have an option to make char unsigned by default. I don't know of a compiler that without flags make char unsigned, but I wouldn't be surprised if they do exist.

--
Mats