'Pointer declaration order matters?

I wonder why the code from exercise 8.3 in C : From Theory to Practice by G.S. Tselikis works, although it shouldn't.

int main() {
  double *ptr, i;
  scanf("%lf", ptr);
  printf("Val = %f\n", *ptr);
  return 0;
}

However, a small change in the variable declaration leads to the expected behaviour (because ptr is not initialized).

int main() {
  double i, *ptr;
  scanf("%lf", ptr);
  printf("Val = %f\n", *ptr);
  return 0;
}

I am using Visual Code Studio and clang (Apple LLVM version 10.0.0 (clang-1000.11.45.5)). Any ideas?



Solution 1:[1]

Both programs have undefined behavior because you pass an invalid address to scanf() to read the numeric value: ptr is not initialized.

If you properly set ptr to point to i, both will behave the same, but the second program can be written more directly with an initializer:

#include <stdio.h>
int main() {
  double *ptr, i;
  if (scanf("%lf", ptr = &i) == 1)
      printf("Val = %f\n", *ptr);
  return 0;
}

vs:

#include <stdio.h>
int main() {
  double i, *ptr = &i;
  if (scanf("%lf", ptr) == 1)
      printf("Val = %f\n", *ptr);
  return 0;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 chqrlie