// C programming tutorial, Nov 16 - Pouya Larjani // Compile with: gcc nov-16.c // Including files #include // Macros #define MAX_INT_WHATEVER 42 #define SQR(x) x*x // Structures (records) struct pair_s { int a; double b; }; // Defining types typedef struct pair_s pair; /* void (in C) = unit (in OCaml) double (C) = float (OCaml) (64-bit floating point) float (C) = 32-bit floating point number, no equivalent in OCaml */ // Prototypes void print_something(pair); // print_something : pair -> void // Main function, only code inside here will be run int main() { // Printing (uses stdio) printf("Hello, World!\n\n"); // Defining variables. Explicit typing, no inference pair p1; // Assigning to record fields p1.a = 42; p1.b = 68.99; // Defining variable and initializing inline pair p2 = {11,22.22}; // Calling functions print_something(p1); print_something(p2); // Random gotcha's with macros! printf("SQR(2+3) = %d\n", SQR(2+3)); // = 2+3*2+3 = 11, not 25!! printf("SQR((2+3)) = %d\n", SQR((2+3))); // = (2+3)*(2+3) = 25 // Pointers and (de/)referencing int *i; // i: int ref int num = 42; // num : int i = # // i := num printf("The de-referenced number is: %d\n", *i); // !i // By ANSI standards main() is supposed to return an int. // Being void is fine but it generates a warning return 0; } // Defining functions void print_something(pair i) { // Format string: %d or %i = int, %f = float and double, %s = string printf("The pair is: (%d, %f)\n", i.a, i.b); }