Miscellaneous topics#

How can we read the return value of main()?#

For example, compile and run the following:

int main(void) { return 42; }

42 becomes the exit code of the program. It is typically interpreted by the terminal as an error code, if the number is greater than 0. If the program ran successfully, it must return 0.

If we avoid the return, then main automatically returns 0.

echo $?
$LASTEXITCODE

You should see as output:

42

Why do I prefer %d over %i in printf?#

You can also use %i for printing integer numbers, which may sound more intuitive, because it begins with i. Most C code uses %d however, because in scanf, %d and %i have a subtle difference. %d only reads decimal numbers, but %i can read other bases like octal and hexadecimal as well. So even %i and %d have the same meaning in printf, I would use %d for consistency between scanf and printf format strings.

#include <stdio.h>
#define INPUT_STRING_SIZE 10

void parse(char parsed_string[], char format_specifier[]) {
  int number;
  int parsed_argument_count = sscanf(parsed_string, format_specifier, &number);
  // scanf reads from the keyboard, but sscanf reads from a string.
  // We use sscanf to avoid keyboard entry
  printf("Parsing %s using %s\n", parsed_string, format_specifier);
  printf("Number of successfully parsed arguments: %d\n",
         parsed_argument_count);
  printf("Read data as decimal integer: %d\n", number);
  puts("");
}

int main() {
  parse("-0xf", "%d");
  parse("-0xf", "%i");
  parse("-0b1111", "%d");
  parse("-0b1111", "%i");
}
Parsing -0xf using %d
Number of successfully parsed arguments: 1
Read data as decimal integer: 0

Parsing -0xf using %i
Number of successfully parsed arguments: 1
Read data as decimal integer: -15

Parsing -0b1111 using %d
Number of successfully parsed arguments: 1
Read data as decimal integer: 0

Parsing -0b1111 using %i
Number of successfully parsed arguments: 1
Read data as decimal integer: -15