1

C written in Emacs

// print1.c --displays some properties of printf()
#include <stdio.h>
int main(void)
{
  int ten = 10;
  int two = 2;

  printf("Doing it right: ");
  printf("%d minus %d is %d\n", ten, 2, ten - two);
  printf("Doing it wrong: ");
  printf("%d minus %d is %d\n", ten); // forgot 2 arguments

  return 0;
}
Welcome to the Emacs shell

Output:

~ $ ./a.exe
Doing it right: 10 minus 2 is 8

Doing it wrong: 10 minus 2 is 8
danglingpointer
  • 4,708
  • 3
  • 24
  • 42
zhyd1997
  • 145
  • 3
  • 15
  • 2
    I'm voting to close this question as off-topic because it relies on external links, and those can break. – Bathsheba Sep 03 '18 at 13:20
  • The arguments of printf doesn't match the format string, therefore the behaviour of your program is undefined. Google "C undefined behaviour" – Jabberwocky Sep 03 '18 at 13:21
  • Thanks for the edit, close vote retracted. – Bathsheba Sep 03 '18 at 13:23
  • 2
    [printf with unmatched format and parameters](https://stackoverflow.com/q/51058371/995714) – phuclv Sep 03 '18 at 13:27
  • It apparently works probably because the 4th invocation of `printf()` finds on the stack the values that were put there on its 2nd invocation. Remove the 2nd invocation of `printf()` and the last one will print garbage. – axiac Sep 03 '18 at 13:53
  • This online C interpreter can tell you that the last `printf` call is undefined: https://taas.trust-in-soft.com/tsnippet/t/61b3753e – Pascal Cuoq Sep 03 '18 at 15:02

1 Answers1

1

It should do nothing of the sort.

The behaviour of your program is undefined.

One manifestation of undefined behaviour is the compiler figuring out what you really wanted to do. Don't ever rely on that though.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483