Sponsored By

Sign in to follow this  
shanenin

Data Types

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

Share this post


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

Share this post


Link to post
Share on other sites

this seems a tad more complicated then python :-)

edit added//

maybe more interesting

Edited by shanenin

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this