Tag Archives: Program Structure

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
statements
}
/* */ /*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)

Initialization

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

Constants

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

Structures

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)
        statement
while statement
for (expr1; expr2; expr3)
        statement
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

<assert.h>
<ctype.h>
<errno.h>
<float.h>
<limits.h>
<locale.h>
<math.h>
<setjmp.h>
<signal.h>
<stdarg.h>
<stddef.h>
<stdio.h>
<stdlib.h>
<string.h>
<time.h>

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
m
        h short
        l long
        L long double
Conversion character:
c
        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

Conversions

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