COMS 3157 Advanced Programming

02 - C language basics

Data types in C

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

        Most 32-bit systems and 64-bit Windows: 4 bytes
        64-bit UNIX (such as our Linux system): 8 bytes
        Java:                                   8 bytes

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:

    ```c 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;

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

extern int x;

1) 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!