C language
Contents
Things to remember about the C language if you want to keep sane
The stack
Symptoms:
- The program counter seems to jump around at random
- Corrupted variables and data.
Declarations
#define
volatile
The volatile keyword tells the compiler that the dollowing object is subject to sudden change in a way that is not described in the source code. For example a RS-232 data register that receive data from the outside. Volatile forces the compiler to generate the code that access the memory location each time instead of cache it in a register. Can be applied to any declaration.
Symptoms of missing volatile statements:
- Code fails when you enable compiler optimizations
- Code fails when interrupts or DMA/Hardware peripherials are enabled
extern
static
const
Read only. Can be applied to any declaration.
const volatile unsigned long int base_address = 0xFFFF;
Pointers
Pointer subtraction
The following statements apply to all pointers in C. They also apply to pointers, other than pointers to members, in C++:
- When one pointer is subtracted from another, the difference is obtained as if by the expression: ((int)a - (int)b) / (int)sizeof(type pointed to)
- If the pointers point to objects whose size is one, two, or four bytes, the natural alignment of the object ensures that the division is exact, provided the objects are not packed.
- For packed or longer types, such as double and struct, both pointers must point to elements of the same array.
Loop constructs
for() direction and signed while do while
switch(var) { case 0: //code break; }
if else
& | ^ ~
Shifts
- Right shift >> The effect on signed numbers is implementation defined, arithmetic shift (ASR) on ARM compilers.
- Left shift <<
- Rotate
- ROR for unsigned int can be implemented as r0 = ((r0 >> n) | (r0 << (32 - n)));
- ROL for unsigned int can be implemented as r0 = ((r0 << n) | (r0 >> (32 - n)));
&& || ==
!= > < >= <=
+= -=
- =
/= >>= <<=
Type specifiers
Data types (ARM C and C++)
- char 8 bits
- short 16 bits
- int 32 bits
- long 32 bits
- long long 64 bits (The low word of a long long is at the low address in little-endian mode, and at the high address in big-endian mode.)
- float 32 bits
- double 64 bits
- long double 64 bits
- All pointers 32 bits
- bool (C++ only) 32 bits
Memory alignement in bits is word length or 32 whichever is smallest
Other
- void
- signed
- unsigned
type casting subroutines void return global vs local
pointers
& (unsigned int *)
arrays multiple dimensions array pointers, 1d, 2d string, terminating character /n /r /t escape characters vs ""
- character and on what type of lines is belongs on
include files "file" <file>
.c
.h
included libraries