Gerardo Cauich
Gerardo Cauich

Reputation: 632

Adding two numbers in char variables read with scanf

I was teaching the C programming language to a friend and we came up with something I could not explain. This is the code we wrote:

#include <stdio.h>

int main(void)
{
    char num1;
    char num2;

    printf("%s", "Enter the first number: ");   
    scanf("%d", &num1);
    printf("%s%d\n", "The number entered is:", num1);

    printf("%s", "Enter the second number: ");
    scanf("%d", &num2);
    printf("%s%d\n", "The number entered is:", num2);

    printf("%s%d\n", "The first number entered was:", num1); /* This was done for testing */
    printf("%s%d\n", "The sum is:", num1+num2);

    return 0;
}

The weird thing is that we tried to do 5 + 6 and we expected to get 11 but instead got 6, I added a line to see what's going on with the first number and it becomes 0 after the second number is read.

I am aware that the variables should be an int (in fact the original code was like that and worked) but my understanding is that a char is a small integer so I thought it would be 'safe' to use if we were adding small numbers.

The code was tested and compiled on a Linux machine with cc and on a Windows machine with cl. The output was the same. On the Windows machine the program throw an error after the addition.

I would like an explanation on why this code is not working as I expected. Thanks beforehand.

Upvotes: 3

Views: 1428

Answers (2)

Yu Hao
Yu Hao

Reputation: 122383

a char is a small integer so I thought it would be 'safe' to use it if we were adding small numbers.

That is correct, char is a small integral type , and it's OK to use it in integer arithmetic(although char may be signed or unsigned which may causes the result unexpected).

But the problem is, a pointer to char can NOT be used in a place where a pointer to int is expected. And this is the case for scanf("%d", &num1);, the second parameter is expected to a of type int *.

Upvotes: 3

nneonneo
nneonneo

Reputation: 179392

You cannot pass a pointer to a different datatype to scanf. scanf will write to memory assuming you gave it a pointer to what it expected (e.g. int for %d), and will exhibit wonderful undefined behaviour if you give it a pointer to a different datatype.

Here, what is most likely happening is that scanf is overwriting e.g. 4 bytes on your stack when your chars only take up 1 byte, so scanf will just be happily writing right over some other variable on your stack.

Upvotes: 4

Related Questions