Search code examples
ccharunsigned-char

Add values to char in c?


Hey guys so I have a char and I want to add some integer/double to it. The char must be a signed char, so I can't just make it an int.

char var = -55;
printf("Char is %d, add, char is now: %d\n", var, var+2);

That code works, but as soon as I want to add a fraction or something...

printf("Char is %d, add, char is now: %d\n", var, var+2/3*2);

It doesn't add at all. Any ideas why? Probably something to do with rounding and whatnot.

Thanks.


Solution

  • Try doing

    printf("Char is %d, add, char is now: %d\n", var, (int)( var+(2/(double)3)*2 ));