Recommended Posts

I was messing around with different data types. first I made this program, it behaved like I thought.

/* this is my program to test how int or char values work */

#include <stdio.h>

main()
{
   int var1, var2, var3;
   var1 = 'A';
   var2 = 'B';
   var3 = var2 + var1;
   printf("the addition of %d and %d is: %d\n",var1, var2, var3);
}

it added the numeric value of 'A' and 'B' then returned the answer

I then changed the code like this, I expected it to fail

/* this is my program to test how int or char values work */

#include <stdio.h>

main()
{
   char var1, var2, var3;
   var1 = 'A';
   var2 = 'B';
   var3 = var2 + var1;
   printf("the addition of %d and %d is: %d\n",var1, var2, var3);
}

my thought was if i declared the varaibles as characters they could not be added, but it added them, but gave them negative numeric values.

why am I getting a -125 for var3, where are these negative numbers coming from?

Edited by shanenin
Link to post
Share on other sites

char is a normal integer type, so you can do whatever you want to it. The name is a historical artifact. The only gotcha is that char can be an alias for either signed char (minimum range -127 .. 127) or unsigned char (minimum range 0 .. 255).

You're getting -125 because on your platform char is signed, with a range of -128 .. 127, and 'A' + 'B' = 65 + 66 = 131, which overflows and wraps around to negative (i.e., the sequence goes 125, 126, 127, -128, -127, -126, -125).

Edited by jcl
Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...