Home > other >  I am not quite understanding the output of the following function
I am not quite understanding the output of the following function

Time:02-16

I wrote a simple sum() function in C with two arguments of integer type. But, while calling the function in main, I passed char type variables. The problem is I am not able to understand the output of the program. Following is the code.:

void sum(int x,int y)
{
    printf(" x=%d  y=%d\n",x,y);
    printf("%d",x y);
}

void main()
{
    char a,b,add;
    printf("Enter two values: ");
    scanf("%c%c",&a,&b);
    sum(a,b);           //calling
} 

If I input a=A and b=A then it should give me the addition of ASCII values of A, i.e. 130, but it is giving me 97. When I try to print the value of x and y, it prints x=65 y=32. I don't understand why it stores 32 in y? Can someone please explain this.

CodePudding user response:

This is because your input was A A, which is A<spacebar>A. The scanf("%c%c",&a,&b) read exactly two characters, A and <spacebar>, which resulted x = 65(A), y= 32(<spacebar>). If you want to get the intended output, your input should be AA.

CodePudding user response:

It seems that you are giving input as A A instead of AA. For the former, x stores 65 and y stores 32 as the ASCII value of space is 32.

  • Related