ArchKudo
ArchKudo

Reputation: 123

How to subtract integers from characters in C?

Brian Kernighnan in his book Programming with C says

By definition, chars are just small integers, so char variables and constants are identical to ints in arithmetic expressions.

Does this mean we can subtract char variable from int ??

I wrote a small piece of code:

#include <stdio.h>

main()
{
    int a ;
    int c;
    a = 1;
    c = 1 - '0' ;
    printf("%d", c);
}

However it gives me output = -47...

What is that I'm doing wrong ?? Are the variables I assigned have the right type??

Upvotes: 2

Views: 12972

Answers (5)

Roberto
Roberto

Reputation: 35

What you are doing is treating with the ASCII code of the chars, each char has an ASCII value assigned.

enter image description here

Now, playing a little with the ASCII of each char you can do things like:

int a;
a = 'a' - 'A' ;
printf("%d", a);

And get 32 as output, due to the ASCII value to 'a' = 97 and for 'A' = 65, then you have 97-65 = 32

Upvotes: 1

Jumabek
Jumabek

Reputation: 68

I think this gives you more clear understanding...

#include <stdio.h>

main()
{
    int a ;
    a = 1;
    printf("%d", char(a+48));
//or printf("%d", char(a+'0')); 
}

Upvotes: 0

Rakib
Rakib

Reputation: 7625

The characters from '0'-'9'' have values 48-57 when converted to integer ('0' = 48, '1' = 49 etc). Read more about ASCII Values. When used in numerical calculation, first they are converted to int, so 1- '0' = 1-48 =-47.

Upvotes: 3

SomeWittyUsername
SomeWittyUsername

Reputation: 18348

You're mixing here the actual operation with the form of representation. printf outputs the data according to the specified format - integer in your case. If you want to print it as a character, switch %d with %c.

Upvotes: 2

David Heffernan
David Heffernan

Reputation: 612884

The output is to be expected. '0' is a char value that, since your compiler presumably uses the ASCII encoding, has value 48. This is converted to int and subtracted from 1. Which gives the value -47.

So the program does what it is expected to do, just not what you might hope it would do. As for what you are doing wrong, it is hard to say. I'm not sure what you expect the program to do, or what problem you are trying to solve.

Upvotes: 6

Related Questions