cs3157-resources

02 - C language basics

Data types in C

char <= short <= int <= long <= long long

unsigned version of all of the above:

unsigned long x = 0, y = 0xff00ff00ff00ff00UL

uint32_t x = 0xffffffff

float is 4 bytes and double is 8 bytes

123.4f
123.4

arrays and pointers

no strings!

Expressions

literals and variables

function calls

assignment:

lvalue = rvalue

pre/post-inc/decrement

x = i++;
x = ++i;

operations

arithmetic:   +, -, *, /, %
comparison:   <, >, ==, !=, <=, >=
logical:      &&, ||, !
bitwise:      ~, &, |, ^, <<, >>

comma expression

conditional expression (ternary operator)

z = (a > b) ? a : b;
z = max(a, b);

any integral expression is also a boolean expression

Statements

if-else:

switch:

loops:

goto

Variable scoping

int x;
x = 0;

{
    int x;
    x = 1;
    printf("%d", x);
}

printf("%d", x);

Storage class

  1. automatic variables

    • also called stack variables, since they are usually stored in process stack (we’ll see what this means later)
    • scope: local to a block
    • lifetime: created on block entrance, destroyed on exit
    • example:

      int foo(int auto_1)
      {
          int auto_2;
      
          {
              int auto_3;
      
              ...
          }
      
          ...
      }
      
  2. static variables

    • “static” has so many meanings in C/C++/Java, so brace yourself!
    • stored in global data section of process memory
    • scope depends on where it is declared: global, file, or block
    • lifetime: created and initialized on program start-up, and persists until the program ends
    • example:

       int global_static = 0;  // visible to other files
      
       static int file_static = 0;  // only visible within this file
      
       int foo(int auto_1)
       {
           static int block_static = 0; // only visible in this block
      
           ...
       }
      

Definition and declaration of global variables

1) *defining* a global variable:

int x = 0; 

extern int x = 0;

2) *declaring* a global variable that is defined in another file:

extern int x;

3) defining a global variable tentatively

int x;

Process address space

Every single process (i.e., a running program) gets 512GB of memory space:

          operating system
             code & data
   512G ---------------------
               stack
        ---------------------
                 |
                 V






                 ^
                 |
        ---------------------
                heap
        ---------------------
          static variables
        ---------------------
            program code
      0 ---------------------

Obviously, computers don’t have that much RAM. It’s virtual memory!