C program has statements written: - C preprocessor language - C proper
#include <stdio.h> // for io
#include <stdbool.h> // for boolean
#include "lib/xalloc.h"
// you can include other things, but not a good idea (never include a .c file)
// notice that inclution have different symbol
header file:
library interface: type definition, function prototype
other preprocessor commands
#define INT_MIN 0x80000000
// preprocessor replaces INT_MIN with 0x80000000
// compiler never sees INT_MIN
#define INT_MAX INT_MIN^-1
// then when you write INT_MAX / 2
// it will replace string as 0x80000000^-1/2
// which C understand as 0x80000000^(-1/2)
#define INT_MAX (INT_MIN^-1)
// this is better
#define MULT(x, y)((x)*(y))
// you can also define function
// observe how many prentheses you need
Compile based on whether a variable is defined
#ifdef DEBUG
printf("Reached this point\n")
#endif
// use else
#ifdef X86_ARCH
#include "arch/x86_optimizations.h"
x86_optimize(code);
#else
generic_optimize(code);
#endif
// we can also check if not defined
#ifndef INT_MIN
#define INT_MIN 0x80000000
#endif
C has no contracts contracts.h:
REQUIRES
ENSURES
ASSERT
Translating contracts
Translating library, variables
TODO: what is the first line
Translating
Translating assertion
Translating all print statements to printf()
Translating alloc
printf("%d", 50); // Prints 50
printf("%d", -213); // Prints -213
printf("%i", -213); // Prints -213
int64_t x = 4294967296; // 4,294,967,296 is 2^32
unsigned int y = 4294967295; // 4,294,967,295 is 2^32 - 1
printf("%d and %d", x, y); // Prints 0 and -1
printf("%u", 500); // Prints 500
printf("%u", -500); // Prints 4294966796
uint64_t x = 4294967296; // 4,294,967,296 is 2^32
printf("%u", x); // Prints 0
printf("%x", 31); // Prints 1f
printf("%X", 31); // Prints 1F
printf("%X", -2); // Prints FFFFFFFE
long a = 4294967296; // 4,294,967,296 is 2^32
printf("%x", a); // Prints 0
printf("%o", 31); // Prints 37
printf("%o", -2); // Prints 37777777776
long a = 4294967296; // 4,294,967,296 is 2^32
printf("%o", a); // Prints 0
More on Printing: Here
so include everything else
also if you have multiple include of the same thing in different file within one compile, bad bad.
Without Garbage Collection, memory will only un-allocate upon program exit.
free(P) whenever you do xalloc(), make sure client know who to free data stored in data structure if needed
Freeing Data Structure:
we pass typedef void entry_free_fn(entry e)
to data structure function
void dict_free(dict_t D, entry_free_fn* Fr)
Lost | Gained |
---|---|
contracts | preprocessor |
safety | whimsical execution |
garbege collection | explicit memory management |
memory initialization | separate compilation |
String in C: https://www.youtube.com/watch?v=90gFFdzuZMw&ab_channel=EngineerMan You should not free the function by passing free(fn_pointer) because functions are not in heap Array Pointer: https://www.youtube.com/watch?v=y2BAaD3fW8A&ab_channel=LuisCeze
Table of Content