General guidlines for C programming


Every C program has a function main()
Curly brackets {} are used to group statements 
into a compound statement.
The simplest C program is:

main()
{
}

Every statement ends with a semicolon

  x = a+b;

Comment starts with /*   ends with */

/* This is a comment */

Simple program -- increment Port A

main()
{
	PORTA = PORTA + 1;
	while(1)
	{
		PORTB = PORTB + 1;
		delay(100);
	}
}
Data Types:

   8-bit                    16-bit
---------------         -----------------
unsigned char             unsigned int
  signed char               signed int


Need to declare variable before using it:

signed char c;
unsigned int i;

Can initialize variable when you define it:

signed char c = 0xaa;
signed int i = 1000;


You tell compiler it you are using signed or unsiged numbers; 
the compiler will figure out whether to use BGT or BHI


Arrays:

unsigned char table[10];  /* Set aside 10 bytes for table */

Can refer to elements table[0] through table[9]

Can initialize and array:

table[] = {0xaa, 0x55, 0xa5, 0x5a};

Arithmetic operators:

 +  (add)           x = a+b;
 -  (subtract) 
 *  (multiply)  
 /  (divide)     
 %  (modulo)      

Logical operators

 &  (bitwise AND)  
 |  (bitwise OR)
 ^  (bitwise XOR)
 << (shift left)
 >> (shift right)
 ~  (complemen)     x = ~a;
 -  (negate)        x = -1;


Check for equality - use ==

if (x == 5)

Check if two conditions true:

if ((x==5) && (y==10))


Check if either of two conditions true:

if ((x==5) || (y==10))

Assign a name to a number

 #define COUNT 5

 
Declare a function:  Tell what parameters it uses, 
what type of number it returns:

int read_port(int port);

If a function doesn't return a number, 
declare it to be type void

void delay(int 100);