0

How are functions 2 and 3 getting this the integers and floats in there printf's? This is very interesting and would love to know why? Does it have to do with the heap or stack?

#include <stdio.h>
#include <stdlib.h>
void function1(void){
int A = 50;
int B = 42;
float X = 3.1459;
float Y = 2.71828;
   printf(“Function 1\n”);
   printf(“%d+%d=%d\n”, A, B, A+B);
   printf(“%f+%f=%f\n”, X, Y, X+Y);
}
void function2(void){
int v1, v2;
float cs, ua;
   printf(“Function 2\n”);
   printf(“v1+v2=%d\n”, v1+v2);
   printf(“cs+ua=%f\n”, cs+ua);
}
void function3(void){
float cs, ua;
int v1, v2;
   printf(“Function 3\n”);
   printf(“v1+v2=%d\n”, v1+v2);
   printf(“cs+ua=%f\n”, cs+ua);
}
Int main(void){
   function1();
   function2();
   function3();
   return 0;
}

Output:

Function 1
50+42=92
3.145900+2.718280=5.864180
Function 2
v1+v2=92
cs+ua=5.864180
Function 3
v1+v2=92
cs+ua=5.864180
  • @OldProgrammer undefined behavior? What does that mean? – Ryan Jevning May 09 '20 at 01:51
  • 2
    Does this answer your question? [What happens to a declared, uninitialized variable in C? Does it have a value?](https://stackoverflow.com/questions/1597405/what-happens-to-a-declared-uninitialized-variable-in-c-does-it-have-a-value) – Mickael B. May 09 '20 at 02:18

1 Answers1

3

This is an undefined behavior: the standards doesn't define what to do in this case when you dont' initialize a local variable.

This means it might depend on the compiler you are using.

What probably happens is that you get some stack space to store your variable, but since you don't set a value, it uses the value that was previously written in that space.

It could have been written by another program, or whatever that used this memory location before. It could be 0 because that memory location was never used, you don't know, the behavior is undefined (you can't define the behavior, you can't predict what the value will be).

Also they are on the stack, the heap is for dynamic memory like when you use malloc.

Mickael B.
  • 4,755
  • 4
  • 24
  • 48