Category Archives: C

C Programming Quick Reference

Program Structure / Functions

type func(type1, …); //function prototype
type name; //variable declaration
int main(void){ //main routine
declarations //local variable declarations
/* */ /*Original C comments (block/multiple line comments*/
// //single line comments recognized by most all compilers
int main(int argc, char *argv[]) //main with args
exit(arg); //terminate execution

C Preprocessor

#include <filename> include library file
#include “filename” include user file
#define name text replacement text
#define name(var) text replacement macro Ex: #define max(a,b) ((a)>(b) ? (a) : (b))
#undefine name undefine
# quoted string in replace Ex: #define msg(a) printf(“%s = %d, #a, (a))
## concatenate args and rescan
#if, #else, #elif, #endif conditional execution
#ifdef, #ifndef is name defined, not defined?
defined(name) name defined?
\ line continuation char

Data Type / Declarations

char character (1 byte)
int integer
float, double real number (single, double precision)
short short (16 bit integer)
long long (32 bit integer)
long long double long (64 bit integer)
signed positive or negative
unsigned non-negative modulo 2m
int*, float*,… pointer to int, float,…
enum tag {name1=value1,…}; enumeration constant
type const name; constant (read-only) value
extern declare external variable
static internal to source file
static local persistent between calls
struct tag {…}; Structure
typedef type name; Create new name for data type
sizeof object size of an object (type is size_t)
sizeof(type) size of a data type (type is size_t)


type name=value; initialize variable
type name[]={value1,…}; initialize array
char name[]=”string”; initialize char string


65536L, -1U, 3.0F Long, unsigned, float
4.2e1 exponential form
0, 0x or 0X octal, hexadecimal Ex: 031 is 25, 0x31 is 49 decimal
‘a’, ‘\ooo’, ‘\xhh’ character constant (char, octal, hex)
\n, \r, \t, \b newline, cr, tab, backspace
\\, \?, \’, \” special characters
“abc…de” string constant (ends with ‘\0’)

Pointers, Arrays and Structures

type *name; declare pointer to type
type *f(); declare function returning pointer to type
type (*pf)(); declare pointer to function returning type
void * generic pointer type
NULL null pointer constant
*pointer object pointed to by pointer
&name address of object name
name[dim] array
name[dim1][dim2]… multi-dimensional array


struct tag { structure template
declarations declaration of members
struct tag name create structure
name.member member of structure from template
pointer -> member member of pointed-to structure Ex: (*p).x and p->x are the same
union single object, multiple possible types
unsigned member: b; bit field with b bits

Operators By Precedence

name, member struct member operator
pointer -> member struct member through pointer
++, — increment, decrement
+, -, !, ~ plus, minus, logical not, bitwise not
*pointer, indirection via pointer, address of object
(type) expr cast expression to type
sizeof size of any object
*, /, % Multiply, divide, modulus (remainder)
+, – Add, subtract
<<, >> left, right shift [bit op]
>, >=, <, <= relational comparisons
==, != Equality comparison
& And [bit op]
^ exclusive or [bit op]
| or (inclusive)
&& logical and
|| logical or
expr1 ? expr2 : expr3 Conditional expression
+=, -=, *=, … assignment operators
, Expression evaluation separator

Unary operators, conditional expression and assignment operators group right to left; all others group left to right

Flow Control

; Statement terminator
{} Block delimiters
break; exit from switch, while, do, for
continue; next iteration of while, do, for
goto label; go to
label: statement label
return expr return value from function

Flow Constructions

if (expr1) statement1
        else if (expr2) statement 2
        else statement3
if statement
while (expr)
while statement
for (expr1; expr2; expr3)
for statement
do statement
        while (expr);
do statement
switch (expr) {
        case const1: statement1 break;
        case const2: statement2 break;
        default: statement
switch statement

ANSI Standard Libraries


Character Class Test <ctype.h>

isalnum(c) Alphanumeric?
isalpha(c) Alphabetic?
iscntrl(c) Control character?
isdigit(c) Decimal digit?
isgraph(c) printing character (not including space)?
islower(c) Lower case letter?
isprint(c) Printing Character (Including space)?
ispunct(c) Printing Character except space, letter, digit?
isspace(c) space, formfeed, newline, cr, tab, vtab?
isupper(c) Upper case letter?
isxdigit(c) Hexadecimal digit?
tolower(c) Convert to lower case
toupper(c) Convert to upper case

String Operations <string.h>
s is a string; cs, ct are constant strings

strlen(s) length of s
strcopy(s, ct) Copy ct to s
strcat(s, ct) Concatenate ct after s
strcmp(cs, ct) compare cs to ct
strcmp(cs, ct, n) compare cs to ct, only first n chars
strchr(cs, c) Pointer to first c in cs
strrchr(cs, c) Pointer to last c in cs
memcpy(s,ct,n) Copy n chars from ct to s
memmove(s,ct,n) Copy n chars from ct to s, may overlap
memcmp(cs,ct,n) Compare n chars of cs with ct
memchr(cs,c,n) Pointer to first c in first n char of cs
memset(s,c,n) Put c into first n chars of s

Input / Output <stdio.h>
Standard I/O

stdin Standard input stream
stdout Standard output stream
stderr Standard Errros stream
EOF End of file (type is int)
getchar() Get a character
putchar(chr) Print a character
printf(“format”, arg1, …) Print formatted data
sprintf(s, “format”, ard1, …) Print to string s
scanf(“format”, &name1, …) Read formatted data
sscanf(s, “format”, &name, …) read from string s
puts(s) Print string s

File I/O

FILE *fp; Declare file pointer
fopen(“name”, “mode”) Pointer to named file modes: r (read), w (write), a (append), b (binary)
getc(fp) Get a character
putc(chr, fp) Write to character
fprintf(fp, “format”, arg1, …) Write to file
fscanf(fp, “format”, arg1, …) Read from file
fread(*ptr, eltsize, n, fp) Read and store n elts to *ptr
fwrite(*ptr, eltsize, n, fp) Write n elts from *ptr to file
fclose(fp) Close file
ferror(fp) non-zero if error
feof(fp) non-zero if already reached EOF
fgets(s, max, fp) read line to string s ( < max chars)
fputs(s, fp) Write string s

Codes for Formatted I/O “%-+ 0w.pmc”

Left justify
+ Print with sign
space Print space if no sign
0 Pad with leading zeros
w Min field width
p Precision
        h short
        l long
        L long double
Conversion character:
        d,i integer
        c Single Char
        f Double (printf)
        f Float(scanf)
        o Octal
        p Pointer
        g,G same as f or e,E depending on exponent
        u Unsigned
        s Char string
        e,E Exponential
        lf Double (scanf)
        x,X Hexadecimal
        n Number of chars written
Conversion character:

Variable Argument Lists <stdarg.h>

va_list ap; Declaration of pointer to arguments
va_start(ap,lastarg); Initialization of argument pointer /* lastarg is last named parameter of the function*/
va_arg(ap,type); Access next unamed tag, update pointer
va_end(ap); Call before exiting function

Standard Utility Functions <stdlib.h>

abs(n) Absolute value of int n
labs(n) Absolute value of long n
div(n,d) Quotient and remainder of ints n,d returns structure with div_t.quot and div_t.rem
ldiv(n,d) Quotient and remainder of longs n,d returns structure with ldiv_t.quot and ldiv_t.rem
rand() Pseudo random integer [0,RAND_MAX]
srand(n) Set random seed to n
exit(status) Terminate program execution
system(s) Pass string s to system for execution


atof(s) Convert string s to double
atoi(s) Convert string s to integer
atol(s) Convert string s to long
strtod(s,&endp) Convert prefix of s to double
strtol(s,&endp,b) Convert prefix of s (base b) to long
strtoul(s,&endp,b) Convert prefix of s (base b) to unsigned long

Storage Allocation

malloc(size), calloc(nobj,size) Allocate storge
newptr = realloc(ptr,size); Change Size of storage
free(ptr); Deallocate storage

Array Functions

bsearch(key,array,n,size,cmpf) Search Array for key
qsort(array,n,size,cmpf) Sort Array ascending order

Time and Date Functions <time.h>

clock() processor time used by program Ex: clock()/CLOCKS_PER_SEC is time in seconds
time() Current calendar time
difftime(time2,time1) time2-time1 in seconds (double)
clock_t,time_t Arithmetic types representing times
struct tm Structure type for calendar time comps
        tm_sec Seconds after minute
        tm_min Minutes after hour
        tm_hour Hours since mindnight
        tm_mday Day of month
        tm_mon Months since January
        tm_year Years since 2000
        tm_wday Days since Sunday
        tm_yday Days since January 1
        tm_isdst Daylight savings time flag
mktime(tp) Convert local time to calendar time
asctime(tp) Convert time in tp to string
ctime(tp) Convert calendar time in tp to local time
gmtime(tp) Convert calendar time to GMT
localtime(tp) Convert calendar time to local time
strftime(s,smax,”format”,tp) tp is a pointer to a structure of type tm

Mathematical Functions <math.h>
Arguments and returned values are double

sin(x), cos(x), tan(x) Trig functions
asin(x), acos(x), atan(x), atan2(y,x), atan2(y,x) Inverse Trig functions
sinh(x), cosh(x), tanh(x) Hyperbolic trig functions
exp(x), log(x), log10(x) Exponentials & logs
ldexp(x,n), frexp(x,&e) Exponentials & logs (2 power)
modf(x,ip), fmod(x,y) Division & remainder
pow(x,y), sqrt(x) Powers
ceil(x), floor(x), fabs(x) rounding

Interger Type Limits <limits.h>
32bit Linux system

CHAR_BIT Bits in char (8)
CHAR_MAX Max value of char (SCHAR_MAX or UCHAR_MAX)
CHAR_MIN Min value of char (SCHAR_MIN or 0)
SCHAR_MAX Max signed char (+127)
SCHAR_MIN Min signed char (-128)
SHRT_MAX Max value of short (+32,767)
SHRT_MIN Min value of short (-32,768)
INT_MAX Max value of int (+2,147,483,647)(+32,767)
INT_MIN Min value of int (-2,147,483,648)(-32,767)
LONG_MAX Max value of long (+2,147,483,647)
LONG_MIN Min value of long (-2,147,483,648)
UCHAR_MAX Max unsigned char (255)
USHRT_MAX Max unsigned short (65,535)
UINT_MAX Max unsigned int (4,294,967,295)(65,535)
ULONG_MAX Max unsigned long (4,294,967,295)

Float Type Limits <float.h>
32bit Linux system

FLT_RADIX Radix of exponent rep (2)
FLT_ROUNDS Floating point rounding mode
FLT_DIG Decimal digits of precision (6)
FLT_EPSILON Smallest x so 1.0f + x ≠ 1.0f (1.1E-7)
FLT_MANT_DIG Number of digits in mantissa
FLT_MAX Max float number (3.4E38)
FLT_MAX_EXP Max Exponent
FLT_MIN Min float number (1.2E-38)
FLT_MIN_EXP Min Exponent
DBL_DIG Decimal digits of precision (15)
DBL_EPSILON Smallest x so 1.0 + x ≠ 1.0 (2.2E-16)
DBL_MANT_DIG Number of digits in mantissa
DBL_MAX Max double number (1.8E308)
DBL_MAX_EXP Max Exponent
DBL_MIN Min double number (2.2E-308)
DBL_MIN_EXP Minimum exponent

Compiling a C Program from Visual C++ 2015 Command Prompt

For quick compiling of C/C++ programs on a Windows PC,  the Visual C++ 2015 Command Prompt is your go to program. Many programs have no need for development in an IDE.

Before you can compile a c/c++ program you will need to install the Microsoft Visual C++ Build Tools 2015.

Once installed you will have a new list of shortcuts in your Start Menu.

Visual C++ Build Tools Start Menu Shortcuts
Visual C++ Build Tools Start Menu Shortcuts

If you right click on any one of the Visual C++ 2015 Programs and choose Open File Location you will also see the extensive list of tools.

Visual C++ Build Tools Explorer Shortcuts
Visual C++ Build Tools Explorer Shortcuts

Depending on what system architecture you are running, open one of the programs. If in doubt select:
Visual C++ 2015 x86 Native Build Tools  Command Prompt
Visual C++ 2015 x64  x86 cross Build Tools  Command Prompt

The following window will appear:

Visual C++ 2015 Build Tools Command Prompt
Visual C++ 2015 Build Tools Command Prompt

To verify that the prompt is functioning property, type cl and the prompt will output the exact same information again.
Note: You can use the Visual C++ 2015 Build Tools Command Prompt the same way you would use the standard command prompt for directory navigation.

  1. To test a simple C program, first create a test directory to hold your test program. md c:\test to create a directory, and then enter cd c:\test to change to that directory. This is where your source files and executable will be stored.
  2. Type notepad test.c  When the  Notepad alert dialog  pops up, choose Yes to create the new test.c file in your current working directory.
  3. In Notepad, enter the following code and save as test.c:
#include <stdio.h>
int main()
printf("Hello World!\n");
getchar(); //used to prevent executable from closing when double clicked
return ;
  1. Now from the Visual C++ Build Tools Command Prompt type: cl test.c. If the program compiled successfully you will see: /out:test.exe and test.obj. In your test folder you will now have the test.c source file along with test.obj and test.exe
  2. To run your newly compiled program simply type test and your program will run in the command prompt. You can also double click the test.exe executable.

To compile a program with more than one source file simply type:

cl test.c test2.c test3.c

The compiler will output a single file called file test.c
To change the name of the output program, add an /out linker option:

cl test.c test2.c test3.c /link /out:mynewprogram.exe

test.c source file

What Is An Arduino?

The Arduino was introduced in 2005 by founders Massimo Banzi, David Cuartielles, Tom Igoe, Gianluca Martino, and David Mellis. The Arduino is not really the board itself or the microprocessor on the board. The Arduino is a hardware/software platform that was designed to provide an inexpensive and easy way for hobbyists, students and professionals to create devices that interact with their environment. The Arduino platform is completely open hardware and open source software.

Arduino boards can be purchased pre-assembled or as do-it-yourself kits. The hardware design information is available for those who would like to assemble an Arduino by hand. The current prices of Arduino boards run around $20-$30 on SparkFun and clones as low as $9 on Amazon

The Arduino platform is a single-board microcontroller designed around an 8-bit Atmel AVR microcontroller, or a 32-bit Atmel ARM. Official Arduinos have used the megaAVR series of chips, specifically the ATmega8, ATmega168, ATmega328, ATmega1280, and ATmega2560. Most boards include a 5 volt linear regulator and a 16 MHz crystal oscillator.

The Arduino platfrom feature a USB interface, 6 analog input pins, as well as 14 digital I/O pins (six of which can produce pulse-width modulated signals) which allows the user to attach various interchangeable add-on modules known as shields or basic breadboards. Many shields are individually addressable via an I²C serial bus, allowing many shields to be stacked and used in parallel. Shields or jumper wires to a breadboard are plugged into the top of the board, via female 0.10-inch (2.5 mm) headers. The Arduino has a number of facilities for communicating with a computer, another Arduino, or other microcontrollers

The Arduino’s microcontroller is also pre-programmed with a boot loader that simplifies uploading of programs to the on-chip flash memory, compared with other devices that typically need an external programmer. Arduino boards are programmed via USB over an RS-232 serial connection implemented using USB-to-serial adapter chips such as the FTDI FT232

The Arduino Platform comes with a simple down-loadable, cross-platform, integrated development environment (IDE) written in JAVA and allows users to write programs for Arduino using C or C++. The code you write is C/C++ syntax but not a valid C/C++ program. An extra include header at the top and a very simple main() function at the bottom, to make it a valid C++ program. The IDE is derived from the IDE for the Processing programming language and the Wiring development platform and contains a C/C++ library called “Wiring”. Wiring was based on the original work done on Processing project in MIT. The Wiring IDE uses the GNU toolchain and AVR Libc to compile programs, and uses avrdude to upload programs to the board. You can program the arduino in standard C using avrstudio and upload with avrdude.

Programming in the Arduino IDE is as simple as creating 2 functions()
1. setup() – a function run once at start up that can be used to define initial environment settings
2. loop() – a function called repeatedly until the board is powered off

A simple program to blink the Arduino LED

Turns on an LED on for one second, then off for one second, repeatedly.

This example code is in the public domain.

// Pin 13 has an LED connected on most Arduino boards.
// give it a name:
int led = 13;

// the setup routine runs once when you press reset:
void setup() {
// initialize the digital pin as an output.
pinMode(led, OUTPUT);

// the loop routine runs over and over again forever:
void loop() {
digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(led, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second

We have hundreds of tutorials in mind for the Arduino Developemnt Platform. We will begin to produce them soon so keep checking back.

For more information right now, check out the offical Arduino page at be sure to check out the Arduino playground which has tons of information to get you started.