1 2 3 4 5 6 | // Single line comment xxxxx // Comment at end of code /* Multi line comment that spans over mutliple lines */ |
1 2 3 4 5 6 7 8 9 10 | // Every language needs a Hello, World! #include <stdio.h> int main() { /* my first program in C */ printf("Hello, World! \n"); return 0; } |
1 2 3 4 5 6 7 8 9 10 11 | // C keywords auto else long switch break enum register typedef case extern return union char float short unsigned const for signed void continue goto sizeof volatile default if static while do int struct _Packed double |
1 2 3 4 5 6 7 8 9 10 11 | // Integer Types char 1 byte -128 to 127 or 0 to 255 unsigned char 1 byte 0 to 255 signed char 1 byte -128 to 127 int 2 or 4 bytes -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647 unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295 short 2 bytes -32,768 to 32,767 unsigned short 2 bytes 0 to 65,535 long 8 bytes or (4bytes for 32 bit OS) -9223372036854775808 to 9223372036854775807 unsigned long 8 bytes 0 to 18446744073709551615 |
1 2 3 4 5 6 7 8 9 | // Integer Literals 85 /* decimal */ 0213 /* octal */ 0x4b /* hexadecimal */ 30 /* int */ 30u /* unsigned int */ 30l /* long */ 30ul /* unsigned long */ |
1 2 3 4 5 | // Floating Point Types float 4 byte 1.2E-38 to 3.4E+38 6 decimal places double 8 byte 2.3E-308 to 1.7E+308 15 decimal places long double 10 byte 3.4E-4932 to 1.1E+4932 19 decimal places |
1 2 3 4 5 6 7 | // Floating point literals 3.14159 /* Legal */ 314159E-5L /* Legal */ 510E /* Illegal: incomplete exponent */ 210f /* Illegal: no decimal or exponent */ .e55 /* Illegal: missing integer or fraction */ |
1 2 3 4 5 | // Void Types void exit (int status); // Function returns void int rand(void); // Function with no arguments void *malloc( size_t size ); // Function returns a pointer to void |
1 2 3 4 5 6 7 8 9 | // String literals "hello, dear" // Single String "hello, \ // String over multiple lines dear" "hello, " "d" "ear". // Single string in parts |
1 2 3 4 5 6 | // Declaring types extern int d = 3, f = 5; // declaration of d and f. int d = 3, f = 5; // definition and initializing d and f. byte z = 22; // definition and initializes z. char x = 'x'; // the variable x has the value 'x'. |
1 2 3 4 5 6 7 | // Default values int 0 char '\0' float 0 double 0 pointer NULL |
1 2 3 4 5 6 7 8 9 10 11 12 | // #define preprocessor // #define identifier value #define LENGTH 10 #define WIDTH 5 #define NEWLINE '\n' #define UNIX 1 #ifdef UNIX printf("UNIX specific function calls go here.\n"); #endif |
1 2 3 4 5 | // Constants const int LENGTH = 10; const int WIDTH = 5; const char NEWLINE = '\n'; |
1 2 3 4 5 6 7 | // Storage Classes auto int month; // Default storage class for all local vars register int miles; // Suggest to use a register static int count = 5; // Keep in existence for lifetime of program extern int size; // Global variable extern void write_extern(); // Global function |
1 2 3 4 5 6 7 8 9 | // Arithmetic Operatios + Adds two operands. A + B = 30 − Subtracts second operand from the first. A − B = -10 * Multiplies both operands. A * B = 200 / Divides numerator by de-numerator. B / A = 2 % Modulus Operator and remainder of after an integer division. B % A = 0 ++ Increment operator increases the integer value by one. A++ = 11 -- Decrement operator decreases the integer value by one. A-- = 9 |
1 2 3 4 5 6 7 8 | // Relational Operators == Checks if the values of two operands are equal or not. If yes, then the condition becomes true. (A == B) is not true. != Checks if the values of two operands are equal or not. If the values are not equal, then the condition becomes true. (A != B) is true. > Checks if the value of left operand is greater than the value of right operand. If yes, then the condition becomes true. (A > B) is not true. < Checks if the value of left operand is less than the value of right operand. If yes, then the condition becomes true. (A < B) is true. >= Checks if the value of left operand is greater than or equal to the value of right operand. If yes, then the condition becomes true. (A >= B) is not true. <= Checks if the value of left operand is less than or equal to the value of right operand. If yes, then the condition becomes true. (A <= B) is true. |
1 2 3 4 5 | // Logical Operators && Called Logical AND operator. If both the operands are non-zero, then the condition becomes true. (A && B) is false. || Called Logical OR Operator. If any of the two operands is non-zero, then the condition becomes true. (A || B) is true. ! Called Logical NOT Operator. It is used to reverse the logical state of its operand. If a condition is true, then Logical NOT operator will make it false. !(A && B) is true. |
1 2 3 4 5 6 7 8 | // Bitwise Operators & Binary AND Operator copies a bit to the result if it exists in both operands. (A & B) = 12, i.e., 0000 1100 | Binary OR Operator copies a bit if it exists in either operand. (A | B) = 61, i.e., 0011 1101 ^ Binary XOR Operator copies the bit if it is set in one operand but not both. (A ^ B) = 49, i.e., 0011 0001 ~ Binary One's Complement Operator is unary and has the effect of 'flipping' bits. (~A ) = ~(60), i.e,. -0111101 << Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. A << 2 = 240 i.e., 1111 0000 >> Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. A >> 2 = 15 i.e., 0000 1111 |
1 2 3 4 5 6 7 8 9 10 11 12 13 | // Assignment Operators = Simple assignment operator. Assigns values from right side operands to left side operand C = A + B will assign the value of A + B to C += Add AND assignment operator. It adds the right operand to the left operand and assign the result to the left operand. C += A is equivalent to C = C + A -= Subtract AND assignment operator. It subtracts the right operand from the left operand and assigns the result to the left operand. C -= A is equivalent to C = C - A *= Multiply AND assignment operator. It multiplies the right operand with the left operand and assigns the result to the left operand. C *= A is equivalent to C = C * A /= Divide AND assignment operator. It divides the left operand with the right operand and assigns the result to the left operand. C /= A is equivalent to C = C / A %= Modulus AND assignment operator. It takes modulus using two operands and assigns the result to the left operand. C %= A is equivalent to C = C % A <<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2 >>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2 &= Bitwise AND assignment operator. C &= 2 is same as C = C & 2 ^= Bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2 |= Bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | // Decision making if(boolean_expression) { /* statement(s) will execute if the boolean expression is true */ } if(boolean_expression) { /* statement(s) will execute if the boolean expression is true */ } else { /* statement(s) will execute if the boolean expression is false */ } if( boolean_expression 1) { /* Executes when the boolean expression 1 is true */ if(boolean_expression 2) { /* Executes when the boolean expression 2 is true */ } } switch(expression) { case constant-expression : statement(s); break; /* optional */ case constant-expression : statement(s); break; /* optional */ /* you can have any number of case statements */ default : /* Optional */ statement(s); } switch(ch1) { case 'A': printf("This A is part of outer switch" ); switch(ch2) { case 'A': printf("This A is part of inner switch" ); break; case 'B': /* case code */ } break; case 'B': /* case code */ } Exp1 ? Exp2 : Exp3; // If Exp1 is True, Exp2 else Exp3 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | // Loops while(condition) { statement(s); } while(condition) { while(condition) { statement(s); } statement(s); } for ( init; condition; increment ) { statement(s); } for ( init; condition; increment ) { for ( init; condition; increment ) { statement(s); } statement(s); } do { statement(s); } while( condition ); do { statement(s); do { statement(s); }while( condition ); } while( condition ); // Infinite Loop for( ; ; ) { printf("This loop will run forever.\n"); } while( some)boolean_expression() ) { do_something() if(some_other_boolean() ) { /* terminate the loop using break statement */ break; } } while( some)boolean_expression() ) { do_something() if(some_other_boolean() ) { /* skip the iteration */ continue; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | // Functions // Definition return_type function_name( parameter list ) { body of the function } // Declaration return_type function_name( parameter list ); // Call by value void add(int x, int y) { return x + y } result = swap(a, b); // Call by reference void swap(int *x, int *y) { // Swap two numbers return; // No return value } swap(&a, &b); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | // Arrays // type arrayName [ arraySize ]; int intArray1[10]; int intArray2[5] = {1, 2, 3, 4, 5}; double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0}; intArray[0] == 1 intArray[4] == 5 // Multi Dimension // type name[size1][size2]...[sizeN]; int a[3][4] = { {0, 1, 2, 3} , /* initializers for row indexed by 0 */ {4, 5, 6, 7} , /* initializers for row indexed by 1 */ {8, 9, 10, 11} /* initializers for row indexed by 2 */ }; // Passing arrays to functions void myFunction(int *param) // Formal parameters as a pointer void myFunction(int param[10]) // Formal parameters as a sized area void myFunction(int param[]) // Formal parameters as an unsized array // Returning arrays from function ( as pointer only ) int * myFunction() // POinters to arrays double *p; double balance[10]; p = balance; *p == balance[0] == *balance *(p+1) == balance[1] == *(balance+1) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | // Pointers int *ip; /* pointer to an integer */ double *dp; /* pointer to a double */ float *fp; /* pointer to a float */ char *ch /* pointer to a character */ int var = 20; /* actual variable declaration */ int *ip; /* pointer variable declaration */ ip = &var; /* store address of var in pointer variable*/ int **pptr; /* pointer to a pointer &var // Address of var ip // Address or var stored in a pointer p *ip // Value of var pointed to by p pptr = &ptr; **pptr // The value of var pointer to by pptr which points to p // Null Pointer, value 0 int *ptr = NULL; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | // Strings ( 1D Arrays ) char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; // Null terminated string char greeting[] = "Hello"; // Automatically null terminated printf("Greeting message: %s\n", greeting ); // Null terminated string methods strcpy(s1, s2); // Copies string s2 into string s1. strcat(s1, s2); // Concatenates string s2 onto the end of string s1. strlen(s1); // Returns the length of string s1. strcmp(s1, s2); // Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2. strchr(s1, ch); // Returns a pointer to the first occurrence of character ch in string s1. strstr(s1, s2); // Returns a pointer to the first occurrence of string s2 in string s1. |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | // Structures /* Syntax struct [structure tag] { member definition; member definition; ... member definition; } [one or more structure variables]; */ struct Books { char title[50]; char author[50]; char subject[100]; int book_id; }; struct Books book1; struct Books book2; strcpy(books1.title, "The C Programming Langauge") printf( "Book 1 title : %s\n", Book1.title); void printBook( struct Books book ); // Pass by value void printBook( struct Books *book ); // Pass by reference // Bit fields struct packed_struct { unsigned int f1:1; unsigned int f2:1; unsigned int f3:1; unsigned int f4:1; unsigned int type:4; unsigned int my_int:9; } pack; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | // Unions /* Syntax union [union tag] { member definition; member definition; ... member definition; } [one or more union variables]; */ union Data { int i; float f; char str[20]; }; union Data data; data.i = 10; printf( "data.i : %d\n", data.i); data.f = 220.5; printf( "data.f : %f\n", data.f); strcpy( data.str, "C Programming"); printf( "data.str : %s\n", data.str); |
1 2 3 4 | // Typedef typedef unsigned char BYTE; BYTE b1, b2; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | // Memory Management void *malloc(size_t size); // This function allocates an array of num bytes and leave them uninitialized. void *calloc(int num, int size); // This function allocates an array of num elements each of which size in bytes will be size. void *realloc(void *address, int newsize); // This function re-allocates memory extending it upto newsize. void free(void *address); // This function releases a block of memory block specified by address. // Allocate Memory Dynamically char name[100]; char *description; strcpy(name, "Zara Ali"); description = malloc( 200 * sizeof(char) ); if( description == NULL ) { // Do something else, allocation failed } description = calloc(200, sizeof(char)); // Alternative // Resizing Memory description = malloc( 30 * sizeof(char) ); description = realloc( description, 100 * sizeof(char) ); if( description == NULL ) { // Do something else, re-allocation failed } // Releasing Memory free(description); // Memopry leaks if you don't !!! |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | // Input / Output Standard input stdin Keyboard Standard output stdout Screen Standard error stderr Your screen #include <stdio.h> int main( ) { int c; printf( "Enter a value :"); c = getchar( ); printf( "\nYou entered: "); putchar( c ); return 0; } #include <stdio.h> int main( ) { char str[100]; printf( "Enter a value :"); gets( str ); printf( "\nYou entered: "); puts( str ); return 0; } #include <stdio.h> int main( ) { char str[100]; int i; printf( "Enter a value :"); scanf("%s %d", str, &i); printf( "\nYou entered: %s %d ", str, i); return 0; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | // File I/O FILE *fopen( const char * filename, const char * mode ); int fclose( FILE *fp ); int fputc( int c, FILE *fp ); int fputs( const char *s, FILE *fp ); int fgetc( FILE * fp ); char *fgets( char *buf, int n, FILE *fp ); r // Opens an existing text file for reading purpose. w // Opens a text file for writing. If it does not exist, then a new file is created. a // Opens a text file for writing in appending mode. If it does not exist, then a new file is created. w+ // Opens a text file for both reading and writing. Truncates the file to zero length a+ // Opens a text file for both reading and writing. Reading from the beginning, writing only appended. // Binary Files size_t fread(void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file); size_t fwrite(const void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file); // Modes == "rb", "wb", "ab", "rb+", "r+b", "wb+", "w+b", "ab+", "a+b" |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | // Command line arguments #include <stdio.h> int main( int argc, char *argv[] ) { if( argc == 2 ) { printf("The argument supplied is %s\n", argv[1]); } else if( argc > 2 ) { printf("Too many arguments supplied.\n"); } else { printf("One argument expected.\n"); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | // Variable Arguments #include <stdio.h> #include <stdarg.h> double average(int num,...) { va_list valist; double sum = 0.0; int i; /* initialize valist for num number of arguments */ va_start(valist, num); /* access all the arguments assigned to valist */ for (i = 0; i < num; i++) { sum += va_arg(valist, int); } /* clean memory reserved for valist */ va_end(valist); return sum/num; } int main() { printf("Average of 2, 3, 4, 5 = %f\n", average(4, 2,3,4,5)); printf("Average of 5, 10, 15 = %f\n", average(3, 5,10,15)); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 | // Pre Processors 1 #define Substitutes a preprocessor macro. 2 #include Inserts a particular header from another file. 3 #undef Undefines a preprocessor macro. 4 #ifdef Returns true if this macro is defined. 5 #ifndef Returns true if this macro is not defined. 6 #if Tests if a compile time condition is true. 7 #else The alternative for #if. 8 #elif #else and #if in one statement. 9 #endif Ends preprocessor conditional. 10 #error Prints error message on stderr. 11 #pragma Issues special commands to the compiler, using a standardized method. // Continuation #define message_for(a, b) \ printf(#a " and " #b ": We love you!\n") // Stringize Operator #define message_for(a, b) \ printf(#a " and " #b ": We love you!\n") message_for(Carole, Debra); // Token Pasting (##) Operator #define tokenpaster(n) printf ("token" #n " = %d", token##n) int token34 = 40; tokenpaster(34); // Defined() Operator #if !defined (MESSAGE) #define MESSAGE "Your Message" #endif // Macros #define MAX(x,y) ((x) > (y) ? (x) : (y)) printf("Max between 20 and 10 is %d\n", MAX(10, 20)); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | // Header Files #include <file> #include "file.h" // Once only header files #ifndef HEADER_FILE #define HEADER_FILE the entire header file file #endif // Computed Includes #if SYSTEM_1 # include "system_1.h" #elif SYSTEM_2 # include "system_2.h" #elif SYSTEM_3 ... #endif // Alternative #define SYSTEM_H "system_1.h" ... #include SYSTEM_H |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | // C Standard Library Header Files <assert.h> Conditionally compiled macro that compares its argument to zero <complex.h> (since C99) Complex number arithmetic <ctype.h> Functions to determine the type contained in character data <errno.h> Macros reporting error conditions <fenv.h> (since C99) Floating-point environment <float.h> Limits of floating-point types <inttypes.h> (since C99) Format conversion of integer types <iso646.h> (since C95) Alternative operator spellings <limits.h> Ranges of integer types <locale.h> Localization utilities <math.h> Common mathematics functions <setjmp.h> Nonlocal jumps <signal.h> Signal handling <stdalign.h> (since C11) alignas and alignof convenience macros <stdarg.h> Variable arguments <stdatomic.h> (since C11) Atomic operations <stdbit.h> (since C23) Macros to work with the byte and bit representations of types <stdbool.h> (since C99) Macros for boolean type <stdckdint.h> (since C23) macros for performing checked integer arithmetic <stddef.h> Common macro definitions <stdint.h> (since C99) Fixed-width integer types <stdio.h> Input/output program utilities General utilities: memory management, program utilities, string conversions, random numbers, algorithms <stdnoreturn.h> (since C11) noreturn convenience macro <string.h> String handling <tgmath.h> (since C99) Type-generic math (macros wrapping math.h and complex.h) <threads.h> (since C11) Thread library <time.h> Time/date utilities <uchar.h> (since C11) UTF-16 and UTF-32 character utilities <wchar.h> (since C95) Extended multibyte and wide character utilities <wctype.h> (since C95) Functions to determine the type contained in wide character data |