-1

I'm come from Java, i want to improve my skill in coding and knowledge of how it's work in deep and i figure that the best language for this is C the mother of all. I'm very excited about how it work c but now please raise me a doubt. Why in C first code don't work and the second yes?

P.s.: I'll skip few steps to speed the code and focus on problem. I'm study C99.

int a,b,c;
int sum = a+b+c;
print scanf ecc...
printf("%d", sum);

The result it will be -1234567 ecc..

And using this code it will work wonderful, this is the mean of a imperative programming?

int a,b,c;
int sum;
print scanf ecc...
sum = a+b+c;
printf("%d", sum);

Sorry for bad english is not my first language, i will improve also that :°D

CivilEngine
  • 47
  • 1
  • 5
  • `Why in C first code don't work and the second yes?` Because in the first one variables `a, b, c` are used uninitialized. – David Ranieri Aug 01 '16 at 17:49

2 Answers2

1

Local variables are not initialized in C, their values are indeterminate. Using an uninitialized local variable leads to undefined behavior.

C is also, exactly like Java, sequential in the absence of loops or gotos. Statements are executed from top to bottom so calling scanf to initialize a variable after you used it will not work. The previous operation will not be redone.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

When you use the first part of the code i.e.

     int a,b,c;
     int sum = a+b+c;
     print scanf ecc...
     printf("%d", sum);

it will first add the a ,b , c and then will produce result with garbage value

while in second case

     int a,b,c;
     int sum;
     print scanf ecc...
     sum = a+b+c;
     printf("%d", sum);

it will read the values by using the scanf and then add those values so will not take the garbage value and produce a wonderful result

Nutan
  • 778
  • 1
  • 8
  • 18