shanenin Posted August 28, 2005 Report Share Posted August 28, 2005 (edited) 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 answerI 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 August 28, 2005 by shanenin Quote Link to post Share on other sites
jcl Posted August 28, 2005 Report Share Posted August 28, 2005 (edited) 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 August 28, 2005 by jcl Quote Link to post Share on other sites
shanenin Posted August 28, 2005 Author Report Share Posted August 28, 2005 (edited) this seems a tad more complicated then python :-)edit added//maybe more interesting Edited August 28, 2005 by shanenin Quote Link to post Share on other sites
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.