-9
#include <stdio.h>
int main ()
{
unsigned char a=250,b=20, c;
c=a+b;
printf ("%d\n",c);
return 0;
}

What can I do for it to show 270? Besides declaring c as int.

Thomas Dickey
  • 51,086
  • 7
  • 70
  • 105

2 Answers2

3

Unsigned char's (assuming char is only eight bits) can only represent 28 numbers, from 0 to 255. You'll need to use another type such as int to represent this.

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
charmlessCoin
  • 754
  • 3
  • 13
  • i was hoping for something a little more clever, as I stated, I don't wish to define c as int – Assura Theorycraft Aug 15 '13 at 23:22
  • 3
    More clever? `puts("270")` is the best answer for a _clever_ response. `printf("%d\n", a + b);` is the next best, as it should convert the result to an int for you anyway. – charmlessCoin Aug 15 '13 at 23:27
1

I'm sorry but you just can't , an unsigned char can hold a maximum of 255

Farouq Jouti
  • 1,657
  • 9
  • 15
  • It's not clear that the value `270` ever has to be stored in an object of type `unsigned char`. One comment suggests `puts("270");`; another suggests `printf("%d\n", a+b);`. Either will work. – Keith Thompson Aug 15 '13 at 23:23
  • is type casting useful for example? after declaring can I convert the unsigned char to an int? or some other method? – Assura Theorycraft Aug 15 '13 at 23:24
  • @KeithThompson I know but I'm talking about the possibility of storing that number in an unsigned char (and you didn't have to vote down to say that) – Farouq Jouti Aug 15 '13 at 23:28
  • @FaroukJouti: Could have been someone else. (It’s best to leave votes out of things for the most part) – Ry- Aug 15 '13 at 23:29
  • @AssuraTheorycraft no that won't work either because in this case their will be a loss of information – Farouq Jouti Aug 15 '13 at 23:30
  • @FaroukJouti: In that case, no cast is necessary, since the result of `a + b` is already of type `int`. (And I didn't downvote your answer; please don't make assumptions.) – Keith Thompson Aug 15 '13 at 23:43
  • @FaroukJouti: It's not related to gcc; it's required by the C standard. (Actually `a + b` is of type `unsigned int` if `UCHAR_MAX > INT_MAX`, but that's impossible for a system with 8-bit bytes.) – Keith Thompson Aug 15 '13 at 23:55
  • @KeithThompson Yeah I just realized how wrong (stupid ?) I am , it took this much to realize , you're absolutely right the sum of both variables is an int :) – Farouq Jouti Aug 15 '13 at 23:59