C Basics

C Language Overview

Why C?

C compilers

REFERENCE: Skim through this C tutorial to start.

The Programming Process

The compilation steps for C

  1. Pre-processing: #include files, definitions
  2. Compile (program = .c/.h files = source code; assembly; machine = object code = .o file)
  3. Link w/library routines
  4. Load into memory
  5. Execute = run in CPU

Preprocessor directives

Code comments

Testing

Assertions are particularly useful in functions to check the validity of parameter values. When an assertion fails, the program will stop running. If it passes (results in true), then the program keeps going.

C Data Types

Primitive data types

WARNING: In C, variables are not initialized for you; they contain junk (prior bit values in memory) and may produce erratic results!!

Integer constants

Booleans

ASCII characters, escape sequences

Size calculations

Type Casting

#include <stdio.h>
int main() {
    // example of up-cast for an explicit conversion
    int i = 45;
    // turn an int (4-byte) into a double (8-byte)
    double j = (double) i; // "(double)" here NOT necessary, compiler will convert
    printf("float %f\n", j);

    // useful up-cast conversion for floating division
    int n1 = 4, n2 = 16;
    printf("floating point division result %f\n", (float) n1 / n2); 

    char c = i; // implicit down-cast conversion, 4-byte to 1-byte (drop 3 bytes)
    printf("character %c\n",c);

    long int l = 23983982;
    int *ptr = (int *) l; // ptr points to memory location 23983982 - a BAD idea!
//    i = *ptr; // uncomment and get a core dump
    
    // casting between pointers and integers sometimes useful however
    short int a[] = {1,2};
    short int *ptr0 = a; // start of array
    short int *ptr1 = a+1; // 2nd element
    
    printf("size of short int is %ld bytes\n",(long int) ptr1 - (long int) ptr0);
    return 0;
}

C Operators

Common Operators

WARNING on equality and assignment:

if (num = 10)  // evaluates to 10, which is considered to be true (non-zero)
if (num == 10) // double equals only evalutes to true if num is in fact a 10

Bitwise operators

Built-in floating-point math functions