#include <stdio.h>
int main()
{
int a, b, sum;
sum = a + b; // initializing variable "sum" here gives incorrect answer to a+b
printf("Enter value a: ");
scanf("%d", &a);
printf("Enter value b: ");
scanf("%d", &b);
printf("sum of %d + %d = %d\n\n", a, b, c);
return 0;
}
This is a program that is supposed to sum two integers. I noticed that when I initialize the variable "sum" before I pass any arguments in my print and scan statements my output is not a correct sum of variables "a" and "b". But when I initialize variable "sum" after the print and scan statements the output is correct:
#include <stdio.h>
int main()
{
int a, b, sum;
printf("Enter value a: ");
scanf("%d", &a);
printf("Enter value b: ");
scanf("%d", &b);
sum = a + b; // variable "sum" is initialized after statement arguments
printf("sum of %d + %d = %d\n\n", a, b, c);
return 0;
}
So my questions are:
- Why does a variable need to be initialized after the statement arguments?
- What is the actual logic behind the order of variable declarations and initializations?
sum = a + b;occurs before eitheraorbhas a defined value. The calculation isn't held over until the values are set; it is done at the point in time represented by its position in the source code. Move the addition after the two inputs. Don't forget to check both input operations to ensure they succeeded before continuing with your calculations.cused inprintf()is not declared anywhere. In the first code sample, in the statementsum=a+bthe values ofaandbare undefined.int a,b,sum; sum=a+b;is not initializingsum. It is assigningsum. Assigningsumto a sum of unknown values, which is UB.