简体   繁体   中英

Unpredictable output of simple C Program

I am practicing c programming from the very beginning, but when I execute simple C program to add two numbers, I got unexpected output, I am not able to figure it out, can anyone provide the detailed explanation of how the compiler works behind the scene for this output.

Here is the mentioned code. I am using basic turbo IDE

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c=0;
clrscr();
printf("Enter two numbers:");
scanf("%d%d", &a,&b);
c=a+b;
printf("sum of two numbers are %d", &c);
getch();
}


Output:

Enter two numbers:1
2
sum of two numbers are -16

You have mistake in line :-

printf("sum of two numbers are %d", &c);`

Change it to :-

printf("sum of two numbers are %d", c);

&c is used when you want to print address.

Modified code :-

#include <stdio.h>
#include <conio.h>
void main()
{
    int a, b, c = 0;
    clrscr();
    printf("Enter two numbers:");
    scanf("%d%d", &a, &b);
    c = a + b;
    printf("sum of two numbers are %d", c); // not &c
    getch();
}

Output :-

Enter two numbers:3                                                                                                                                                                    
5                                                                                                                                                                                      
sum of two numbers are 8  

Turbo c is very outdated.Try gcc (IDEs like CodeBlocks) . Also make sure that your code is intended properly.

The problem seems to be that you used the address-of operator on the variable c where you did not need to. &c is a pointer to c , so when you print it out you are actually trying to print the memory address of c rather than the integer value stored there, leading to unexpected output. So

printf("sum of two numbers are %d", &c);

should become

printf("sum of two numbers are %d", c);

您输入的printf语法错误,请使用以下命令: printf("sum of two numbers are %d",c);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM