{"content":{"id":681,"title":"'Build Your Own Lisp' Solutions: 4.6","body":"\u003cp\u003e\u003cb\u003eQ:\u003c/b\u003e What happens when you pass \u003ci\u003eprintf\u003c/i\u003e a variable that does not match the pattern?\r\n\u003cbr\u003e\r\n\u003cp\u003e\u003cb\u003eA:\u003c/b\u003e\u003c/p\u003e\r\n\u003cpre\u003e\u003ccode class=\"cpp\"\u003e#include \u0026ltstdio.h\u0026gt\r\n\r\nint main(void)\r\n{\r\n // This depends heavily on the kind of mistake you want to make. Some \r\n // examples:\r\n\r\n // A character is really a number, so this is fine.\r\n printf(\"%c\\n\", 109);\r\n // And vice-versa.\r\n printf(\"%d\\n\", 'm');\r\n // A string really just points to the memory address of the first character,\r\n // and %d will try to interpret that address as a base ten number, so this\r\n // will be something different every time you run the program.\r\n printf(\"%d\\n\", \"moo\");\r\n\r\n // These examples all happen to give you something, but the compiler has no \r\n // idea what to do with something like 'printf(\"%s\\n\", 13);', and will give \r\n // you a Segment Fault error.\r\n\r\n return 0;\r\n}\r\n\u003c/code\u003e\u003c/pre\u003e\r\n\u003cpre\u003e\u003ccode class=\"lisp\"\u003e\u0026gt ./wrong \r\nm\r\n109\r\n340750348\r\n\u003c/code\u003e\u003c/pre\u003e","publication_date":"2019-05-31T00:00:00.000Z","created_at":"2019-04-30T01:26:32.000Z","updated_at":"2019-05-01T18:38:09.000Z","user_id":1,"rating":null},"tags":"\u003ca class=\"changeable-title\" href=\"/q?tag=c\"\u003ec\u003c/a\u003e \u003ca class=\"changeable-title\" href=\"/q?tag=lisp\"\u003elisp\u003c/a\u003e \u003ca class=\"changeable-title\" href=\"/q?tag=build_your_own_lisp\"\u003ebuild_your_own_lisp\u003c/a\u003e \u003ca class=\"changeable-title\" href=\"/q?tag=answers\"\u003eanswers\u003c/a\u003e \u003ca class=\"changeable-title\" href=\"/q?tag=programming\"\u003eprogramming\u003c/a\u003e"}

'Build Your Own Lisp' Solutions: 4.6

Q: What happens when you pass printf a variable that does not match the pattern?

A:

#include <stdio.h>

int main(void)
{
  // This depends heavily on the kind of mistake you want to make. Some 
  // examples:

  // A character is really a number, so this is fine.
  printf("%c\n", 109);
  // And vice-versa.
  printf("%d\n", 'm');
  // A string really just points to the memory address of the first character,
  // and %d will try to interpret that address as a base ten number, so this
  // will be something different every time you run the program.
  printf("%d\n", "moo");

  // These examples all happen to give you something, but the compiler has no 
  // idea what to do with something like 'printf("%s\n", 13);', and will give 
  // you a Segment Fault error.

  return 0;
}
> ./wrong 
m
109
340750348