'I am not quite understanding the output of the following function
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.
Solution 1:[1]
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.
Solution 2:[2]
If you want to store 124abc in a integer variable then it will store only 124. And in the definition of character constant/variable it can save all ASCII 255 character's which include also space(spacebar),tab(tab key),newline(enter key). so when you run code and the screen show "Enter two values: ". You type 'A' which store in variable 'a'. Now you press space bar which is also a character constant which have value of ASCII 32 store into variable 'b'. so avoid this situation you should put a space before %c so it never read enter key or space bar. Or use fflush(stdin) function.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | onapte |
| Solution 2 | Sumit Baloda |
