0

I'm really confused about the result of the following code:

#include <stdio.h>
#include <stdlib.h>

int one(int a, int b) {
    int k, t;
    k = a - b;
    t = a + b + 1;
    if (k % 2 == 0) return t;
    else return 0;
}

int two(int x, int y) {
    int m;
    printf("%d\n", m);
    return m + x + y;
}

main() {
    int result = two(5, one(4, 3));
    // printf("%d\n", one(4, 3));
    printf("result is %d\n", result);
}

one(4, 3) returns 0, which is not surprising. But I don't understand why two(5, 0) returns 8. In other words, m takes on the value 3 without being initialized. How did this happen?

zhuhan
  • 193
  • 1
  • 1
  • 8

1 Answers1

1

C does not automatically initialize values to 0 when you define them. Technically, reading that data before you initialize it is undefined behavior. In practice, this normally results in a garbage value containing whatever data was stored in that location previously.

PC Luddite
  • 5,883
  • 6
  • 23
  • 39