effective-c, notes

These are my notes on Robert C. Seacord's "Effective C: An Introduction to Professional C Programming."

Chapter 1

Hello world

#include <stdio.h>
#include <stdlib.h>
int main(void) {
    puts("hi there world...");
    return EXIT_SUCCESS;
}

EXIT SUCCESS is a macro that typically expands to 0.

#include <stdio.h>
#include <stdlib.h>
int main(void) {
    if (puts("hi there world...") == EOF) {
        return EXIT_FAILURE;
        // code here will never run
    }
    return EXIT_SUCCESS;
    // code here will never run
}

This version of our initial program checks to see if puts returns EOF (a failure state). If it returns EOF the programs returns EXIT FAILURE which evaluates to a nonzero value. This allows other programs to check if this program succeeded or failed.

puts writes to stdout. Fun and fine for initial needs, but sometimes we need to format text.

printf("%s\n", "hi there world!");

printf returns status differently than puts, so we can't just drop it in to our code as is. printf returns the number of characters printed, unless there is an error, then it returns a negative number.

#include <stdio.h>
#include <stdlib.h>
int main(void) {
    if (printf("hey hey hey!") < 0) {
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}

Compilers

C is a compiled language, so before code can run you have to comile it.

…me feeling smug, because org-babel means I can run code written in C directly within my notes.

Big names in this game include gcc and clang.

I'm also interested in exploring musl libc, not mentioned in this book, as well as Plan9 C, and Tiny C Compiler (aka tcc).

Portability

For maximum portability only use C language features and libraries that are specified in the standard.

Chapter 2

Objects, functions, types, and pointers

Declaring variables

#include <stdio.h>

void swap(int, int);

int main(void) {
    int a = 21;
    int b = 17;

    swap(a, b);
    printf("main: a = %d, b = %d\n", a, b);
    return 0;
}

Whilst you are able to declare multiple variables in a single declaration I think it looks like garbage.

char *src;    // src has a type of char *
char c;       // c has a type of char
int x;        // x has a type int
int y[5];     // y is an array of 5 elements of type int
int m[12];    // m is an array of 12 elements of type int
int n[15][3]; // n is an array of 15 arrays of 3 elements of type int