You are on page 1of 2

C Reference Card (ANSI) Constants Flow of Control

suffix: long, unsigned, float 65536L, -1U, 3.0F statement terminator ;


Program Structure/Functions exponential form 4.2e1 block delimiters { }
type fnc(type 1 , . . . ); function prototype prefix: octal, hexadecimal 0, 0x or 0X exit from switch, while, do, for break;
type name; variable declaration Example. 031 is 25, 0x31 is 49 decimal next iteration of while, do, for continue;
int main(void) { main routine character constant (char, octal, hex) 'a', '\ooo', '\xhh' go to goto label;
declarations local variable declarations newline, cr, tab, backspace \n, \r, \t, \b label label: statement
statements special characters \\, \?, \', \" return value from function return expr
} string constant (ends with '\0') "abc. . . de" Flow Constructions
type fnc(arg 1 , . . . ) { function definition if statement if (expr 1 ) statement 1
declarations local variable declarations Pointers, Arrays & Structures else if (expr 2 ) statement 2
statements declare pointer to type type *name; else statement 3
return value; declare function returning pointer to type type *f(); while statement while (expr )
} declare pointer to function returning type type (*pf)(); statement
/* */ comments generic pointer type void * for statement for (expr 1 ; expr 2 ; expr 3 )
int main(int argc, char *argv[]) main with args null pointer constant NULL statement
exit(arg); terminate execution do statement do statement
object pointed to by pointer *pointer
while(expr );
address of object name &name
C Preprocessor array name[dim] switch statement switch (expr ) {
case const 1 : statement 1 break;
include library file #include <filename> multi-dim array name[dim 1 ][dim 2 ]. . . case const 2 : statement 2 break;
include user file #include "filename" Structures default: statement
replacement text #define name text struct tag { structure template }
replacement macro #define name(var ) text declarations declaration of members
Example. #define max(A,B) ((A)>(B) ? (A) : (B)) }; ANSI Standard Libraries
undefine #undef name create structure struct tag name <assert.h> <ctype.h> <errno.h> <float.h> <limits.h>
quoted string in replace # member of structure from template name.member <locale.h> <math.h> <setjmp.h> <signal.h> <stdarg.h>
Example. #define msg(A) printf("%s = %d", #A, (A)) member of pointed-to structure pointer -> member <stddef.h> <stdio.h> <stdlib.h> <string.h> <time.h>
concatenate args and rescan ## Example. (*p).x and p->x are the same
conditional execution #if, #else, #elif, #endif single object, multiple possible types union
Character Class Tests <ctype.h>
is name defined, not defined? #ifdef, #ifndef bit field with b bits unsigned member : b; alphanumeric? isalnum(c)
name defined? defined(name) alphabetic? isalpha(c)
line continuation char \ Operators (grouped by precedence) control character? iscntrl(c)
Data Types/Declarations struct member operator name.member decimal digit? isdigit(c)
struct member through pointer pointer ->member printing character (not incl space)? isgraph(c)
character (1 byte) char lower case letter? islower(c)
integer int increment, decrement ++, --
printing character (incl space)? isprint(c)
real number (single, double precision) float, double plus, minus, logical not, bitwise not +, -, !, ~
printing char except space, letter, digit? ispunct(c)
short (16 bit integer) short indirection via pointer, address of object *pointer , &name
space, formfeed, newline, cr, tab, vtab? isspace(c)
long (32 bit integer) long cast expression to type (type) expr
upper case letter? isupper(c)
double long (64 bit integer) long long size of an object sizeof
hexadecimal digit? isxdigit(c)
positive or negative signed multiply, divide, modulus (remainder) *, /, % convert to lower case tolower(c)
non-negative modulo 2m unsigned add, subtract +, - convert to upper case toupper(c)
pointer to int, float,. . . int*, float*,. . .
enumeration constant enum tag {name 1 =value 1 ,. . . };
left, right shift [bit ops] <<, >> String Operations <string.h>
constant (read-only) value type const name; relational comparisons >, >=, <, <= s is a string; cs, ct are constant strings
declare external variable extern equality comparisons ==, != length of s strlen(s)
internal to source file static and [bit op] & copy ct to s strcpy(s,ct)
local persistent between calls static concatenate ct after s strcat(s,ct)
no value void exclusive or [bit op] ^
compare cs to ct strcmp(cs,ct)
structure struct tag {. . . }; or (inclusive) [bit op] | only first n chars strncmp(cs,ct,n)
create new name for data type typedef type name; logical and && pointer to first c in cs strchr(cs,c)
size of an object (type is size_t) sizeof object pointer to last c in cs strrchr(cs,c)
logical or ||
size of a data type (type is size_t) sizeof(type) copy n chars from ct to s memcpy(s,ct,n)
conditional expression expr 1 ? expr 2 : expr 3
Initialization copy n chars from ct to s (may overlap) memmove(s,ct,n)
assignment operators +=, -=, *=, . . . compare n chars of cs with ct memcmp(cs,ct,n)
initialize variable type name=value; expression evaluation separator , pointer to first c in first n chars of cs memchr(cs,c,n)
initialize array type name[]={value 1 ,. . . }; Unary operators, conditional expression and assignment oper- put c into first n chars of s memset(s,c,n)
initialize char string char name[]="string"; ators group right to left; all others group left to right.
c 2007 Joseph H. Silverman Permissions on back. v2.2
°
C Reference Card (ANSI) Standard Utility Functions <stdlib.h> Mathematical Functions <math.h>
absolute value of int n abs(n) Arguments and returned values are double
Input/Output <stdio.h> absolute value of long n labs(n) trig functions sin(x), cos(x), tan(x)
Standard I/O quotient and remainder of ints n,d div(n,d) inverse trig functions asin(x), acos(x), atan(x)
standard input stream stdin returns structure with div_t.quot and div_t.rem arctan(y/x) atan2(y,x)
standard output stream stdout quotient and remainder of longs n,d ldiv(n,d) hyperbolic trig functions sinh(x), cosh(x), tanh(x)
standard error stream stderr returns structure with ldiv_t.quot and ldiv_t.rem exponentials & logs exp(x), log(x), log10(x)
end of file (type is int) EOF pseudo-random integer [0,RAND_MAX] rand() exponentials & logs (2 power) ldexp(x,n), frexp(x,&e)
get a character getchar() set random seed to n srand(n) division & remainder modf(x,ip), fmod(x,y)
print a character putchar(chr ) terminate program execution exit(status) powers pow(x,y), sqrt(x)
print formatted data printf("format",arg 1 ,. . . ) pass string s to system for execution system(s) rounding ceil(x), floor(x), fabs(x)
Conversions
print to string s sprintf(s,"format",arg 1 ,. . . )
convert string s to double atof(s) Integer Type Limits <limits.h>
read formatted data scanf("format",&name 1 ,. . . )
read from string s sscanf(s,"format",&name 1 ,. . . ) convert string s to integer atoi(s) The numbers given in parentheses are typical values for the
print string s puts(s) convert string s to long atol(s) constants on a 32-bit Unix system, followed by minimum re-
File I/O convert prefix of s to double strtod(s,&endp) quired values (if significantly different).
declare file pointer FILE *fp; convert prefix of s (base b) to long strtol(s,&endp,b) CHAR_BIT bits in char (8)
pointer to named file fopen("name","mode") same, but unsigned long strtoul(s,&endp,b) CHAR_MAX max value of char (SCHAR_MAX or UCHAR_MAX)
modes: r (read), w (write), a (append), b (binary) Storage Allocation CHAR_MIN min value of char (SCHAR MIN or 0)
get a character getc(fp) allocate storage malloc(size), calloc(nobj,size) SCHAR_MAX max signed char (+127)
write a character putc(chr ,fp) change size of storage newptr = realloc(ptr,size); SCHAR_MIN min signed char (−128)
write to file fprintf(fp,"format",arg 1 ,. . . ) deallocate storage free(ptr); SHRT_MAX max value of short (+32,767)
read from file fscanf(fp,"format",arg 1 ,. . . ) Array Functions SHRT_MIN min value of short (−32,768)
read and store n elts to *ptr fread(*ptr,eltsize,n,fp) search array for key bsearch(key,array,n,size,cmpf) INT_MAX max value of int (+2,147,483,647) (+32,767)
write n elts from *ptr to file fwrite(*ptr,eltsize,n,fp) sort array ascending order qsort(array,n,size,cmpf) INT_MIN min value of int (−2,147,483,648) (−32,767)
LONG_MAX max value of long (+2,147,483,647)
close file fclose(fp) Time and Date Functions <time.h> LONG_MIN min value of long (−2,147,483,648)
non-zero if error ferror(fp)
non-zero if already reached EOF feof(fp) processor time used by program clock() UCHAR_MAX max unsigned char (255)
read line to string s (< max chars) fgets(s,max,fp) Example. clock()/CLOCKS_PER_SEC is time in seconds USHRT_MAX max unsigned short (65,535)
write string s fputs(s,fp) current calendar time time() UINT_MAX max unsigned int (4,294,967,295) (65,535)
Codes for Formatted I/O: "%-+ 0w.pmc" time2 -time1 in seconds (double) difftime(time2 ,time1 ) ULONG_MAX max unsigned long (4,294,967,295)
arithmetic types representing times clock_t,time_t
- left justify
structure type for calendar time comps struct tm Float Type Limits <float.h>
+ print with sign
space print space if no sign tm_sec seconds after minute The numbers given in parentheses are typical values for the
0 pad with leading zeros tm_min minutes after hour constants on a 32-bit Unix system.
w min field width tm_hour hours since midnight FLT_RADIX radix of exponent rep (2)
p precision tm_mday day of month FLT_ROUNDS floating point rounding mode
m conversion character: tm_mon months since January FLT_DIG decimal digits of precision (6)
h short, l long, L long double tm_year years since 1900 FLT_EPSILON smallest x so 1.0f + x 6= 1.0f (1.1E − 7)
c conversion character: tm_wday days since Sunday FLT_MANT_DIG number of digits in mantissa
d,i integer u unsigned tm_yday days since January 1 FLT_MAX maximum float number (3.4E38)
c single char s char string tm_isdst Daylight Savings Time flag FLT_MAX_EXP maximum exponent
f double (printf) e,E exponential convert local time to calendar time mktime(tp) FLT_MIN minimum float number (1.2E − 38)
f float (scanf) lf double (scanf) convert time in tp to string asctime(tp) FLT_MIN_EXP minimum exponent
o octal x,X hexadecimal convert calendar time in tp to local time ctime(tp) DBL_DIG decimal digits of precision (15)
p pointer n number of chars written convert calendar time to GMT gmtime(tp) DBL_EPSILON smallest x so 1.0 + x 6= 1.0 (2.2E − 16)
g,G same as f or e,E depending on exponent convert calendar time to local time localtime(tp) DBL_MANT_DIG number of digits in mantissa
format date and time info strftime(s,smax,"format",tp) DBL_MAX max double number (1.8E308)
Variable Argument Lists <stdarg.h> tp is a pointer to a structure of type tm DBL_MAX_EXP maximum exponent
declaration of pointer to arguments va_list ap; DBL_MIN min double number (2.2E − 308)
initialization of argument pointer va_start(ap,lastarg); DBL_MIN_EXP minimum exponent
lastarg is last named parameter of the function
access next unnamed arg, update pointer va_arg(ap,type)
call before exiting function va_end(ap); c 2007 Joseph H. Silverman
January 2007 v2.2. Copyright °
Permission is granted to make and distribute copies of this card pro-
vided the copyright notice and this permission notice are preserved on
all copies.
Send comments and corrections to J.H. Silverman, Math. Dept., Brown
Univ., Providence, RI 02912 USA. hjhs@math.brown.edui

You might also like