Tag Archives: functions

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

PHP Quick Reference

Array Functions
array_diff (arr1, arr2 …)
array_filter (arr, function)
array_flip (arr)
array_intersect (arr1, arr2 …)
array_merge (arr1, arr2 …)
array_pop (arr)
array_push (arr, var1, var2 …)
array_reverse (arr)
array_search (sysrecon, arr)
array_walk (arr, function)
count (count)
in_array (sysrecon, phpquickrefference)

String Functions
crypt (str, salt)
explode (sep, str)
implode (glue, arr)
nl2br (str)
sprints (frmt, args)
strip_tags (str, allowed_tags)
str_replace (search, replace, str)
strpos (str, sysrecon)
strive (str)
strstr (str, sysrecon)
strtolower (str)
strtoupper (str)
substr (string, start, len)

Filesystem Functions
clearstatcache ()
copy (source, dest)
fclose (handle)
fgets (handle, len)
file (file)
filetime (file)
filesize (file)
file_exists (file)
fopen (file, mode)
fread (handle, len)
fwrite (handle, str)
readfile (file)

fopen() Modes
r         Read
r+      Read and write, prepend
w       Write, truncate
w+    Read and write, truncate
a        Write, append
a+     Read and write, append

Regular Expression Functions
ereg (pattern, str)
split (pattern, str)
ereg_replace (pattern, replace, str)
preg_grep (pattern, arr)
preg_match (pattern, str)
preg_match_all (pattern, str, arr)
preg_replace (pattern, replace, str)
preg_split (pattern, str)

Regular Expression Syntax
^                    Start string
$                     End String
.                       Any single character
(a|b)              a or b
(…)                Group section
[abc]              Item in range (a,b or c)
[^abc]           Not in range (not a,b or c)
\s                     White space
a?                     Zero or one of a
a*                     Zero or more of a
a*?                   Zero or more of a, ungreedy
a+                    One or more of a
a+?                  One or more of a, ungreedy
a{3}                 Exactly 3 of a
a{3,}                3 or more of a
a{,6}                Up to 6 of a
a{3,6}             3 to 6 of a
a{3,6}?           3 to 6 of a, ungreedy
\                        Escape character
[:punct:]       Any punctuation symbol
[:space:]       Any space character
{;blank:]        Space or tab

PCRE Modifiers
i         Case insensitive
s         Period matches new ine
m       ^ and $ match lines
U       Ungreedy matching
e        Evaluate replacement
x        Pattern over several lines

Date and Time Functions
checkdate (month, day, year)
date (format, timestamp)
getdate (timestamp)
mktime (hr, min, sec, month, day, yr)
strftime (formatstring, timestamp)
strtotime (str)

Date Formatting
Y         4 digit year (2016)
y          2 digit year (16)
F          Long month (November)
M        Short month (Nov)
m         Month (01 to 12) //with leading zeros
n          Month (1 to 12)
D         Short day name (Fri)
l           Long day name (Friday) (lowercase L)
d         Day (01 to 31) //with leading zeros
j          Day (1 to 31)
h        12 Hour (01 to 12) //with leading zeros
g        12 Hour (1 to 12)
H       24 Hour (00 to 23) //with leading zeros
G       24 Hour (0 to 23)
i         Minutes (00 to 59) //with leading zeros
s        Seconds (00 to 59) //with leading zeros
w      Day of week (0 to 6) //0 is Sunday, 6 is Saturday
z        Day of year (0 to 365)
W      Week of year ( 1 to 53) //Week that overlaps two years belongs to the year that contains the most days of that week. date(“W”, mktime(0,0,0,12,8,$year)) always gives correct number of weeks in $year.
t         Days in month (28 to 31
a         am or pm
A        AM or PM
B        Swatch Internet Time (000 to 999)
S         Ordinal Suffix (st,nd,rd,th)
T         Timezone of machine (GMT)
Z         Timezone offset (seconds)
O        Difference to GMT (hours) (e.g., +0200)
I           Daylight saving (1 or 0)
L          Leap year (1 or 0)
U         Seconds since Epoch //The Epoch is the 1st of January 1970
c           ISO 8601 (PHP5) //2016-06-09T08:54:23+1:00
r           RFC 2822 //Thu, 09 June 2016 08:54:23 +0100