Your SlideShare is downloading. ×
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

# C Reference Card (Ansi) 2

791
views

Published on

Guia de referência rápida sobre C.

Guia de referência rápida sobre C.

Published in: Technology, Business

0 Comments
0 Likes
Statistics
Notes
• Full Name
Comment goes here.

Are you sure you want to Yes No
Your message goes here
• Be the first to comment

• Be the first to like this

No Downloads
Views
Total Views
791
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
29
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

### Transcript

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