CS 355 - Systems Programming:
Unix/Linux with C

C Programming Review

Basic structure of a C program

/* This program doesn't do a whole lot */

#include <stdio.h>
int main()
{
    printf("Hello, world!\n");
    return 0;
}

More info

Useful primitive data types

int x = 0;
long y = 1;
char c = 'a';
float f = 1.0;

More info

Conditional execution

if ( /* condition */ ) {
    /* Execute these statements if the condition is TRUE */
}
if ( /* condition */ ) {
    /* Execute these statements if the condition is TRUE */
}
else {
    /* Execute these statements if the condition is FALSE */
}

More info

Switch/case

switch ( /* expression */ ) {
case /* value 1 */ :
  /* Code 1 */
  break;
case /* value 2 */ :
  /* Code 2 */
  break;
case /* value N */ :
  /* Code N */
  break;
default:
  /* Code */
  break;
}

More info

Loops

for ( /* variable initialization */ ;
      /* condition */ ;
      /* variable update */ ) {
  /* Code to execute while the condition is true */
}
do {
  /* Code to execute while the condition is true */
} while ( /* condition */ );
while (  /* condition */ )  {
  /* Code to execute while the condition is true */
}

More info

Functions

/* general format */
return_type function_name ( arg_type arg1, ..., arg_type argN );
/* prototype of a function */
int product (int, int);

int main() {
   int iA = 1, iB = 2;
   int iC = product(iA, iB);
}

/* implementation of a function */
int product(int iArg1, int iArg2) {
   return iArg1 * iArg2;
}

More info

Pointers

/* general syntax */
variable_type *pointer_name;

int *piIntegerPointer;
int *piPtr1, *piPtr2;
int *piPointer, iNonPointer;
#include <stdio.h>

int main(){
   int iInt;
   int *piPtr;

   piPtr = &iInt;          /* get the address of... */
   scanf("%d", &iInt);     /* get the address of... */
   printf("%d\n", *piPtr); /* dereference the pointer */
}
#include <stdlib.h>

float *pfPtr = malloc(sizeof(pfPtr));
/* use pfPtr ... */
free(pfPtr);

More info

Arrays

int iaNumbers[100];
int i;

for(i=0; i<100; i++)
   printf("iaNumbers[%d] = %d\n", i, iaNumbers[i]);
char cTmp[100] = "Hello, world!";
char *cpString;

cpString = cTmp;

printf("%s", cpString);  /* print the entire string */

char *p;                 /* print the entire string, one char at a time */
for(p=cpString; p!=0; p++)
   printf("%c", *p);

More info

Structures

struct database {
  int iID;
  int iAge;
  float fSalary;
};

int main()
{
  struct database employee;
  employee.iAge = 22;
  employee.iID = 1;
  employee.fSalary = 12000.21;

  struct database *ptr;
  ptr = &employee;
  printf("%d\n", ptr->iAge);
}

More info

Working with command line parameters

#include <stdio.h>
int main(int ac, char *av[])
{
   int i;
   for(i=0; i<ac; i++)
      printf("Parameter %d: %s\n", i, av[i]);
   return 0;
}