Skytopia > Articles > Quick reference to the most common commands used in C/C++    (article created 05/07/2006)

This page is now largely deprecated.
Please visit the C/C++ (+ Java) reference page

Quick reference to the most common commands used in C/C++

I knocked up this page as a quick reference to many useful commands used in the C/C++ programming language. They're mainly geared towards C though I'll include some C++ only commands when I feel like it.
Basically, I would have died for a web page like this when I first started out learning C (I came from a Java background, but found C many times faster for my first application conversion!). Hope you all find it useful! If you'd like to comment on this page, please email me

Basic program template


int main()                    // According to compiler, may require "int argc, char *argv[]" in brackets.
	printf("Hello, world\n");

Basic Operators and C/C++ syntax

+ * - / %                     // Simple math functions same as usual. Plus, multiply, subtract, divide, and modulus (which means take the 'remainder' (e.g. 5 % 17 = 2)). Use of the term '++' in n++ for example, is shorthand for n=n+1.
// hidden                     // 'Comment' or 'quote out' a line from that point on, to make it 'invisible' to the compiler.
/* hidden */                  // Like above, but quotes out a whole section. /* Begins the section, and */ ends it.
&&                            // AND operator
||                            // OR operator
!                             // NOT operator
=                             // Means simple assignment. For example: n=10
==                            // Means 'equals to'. 1==2 is false etc. Be very careful not to mix this up with assignment (=).
!=                            // Means 'not equals to'. 1!=2 is true etc.
<                             // Less than. For example, 3<7 is true. Also use <= for 'less than or equals to'.
>                             // More than. For example, 3>7 is false. Also use >= for 'more than or equals to'.

Bread and Butter Commands

if    (a==b) { blah...  }          // If a equals b, then do whatever is in the curly brackets.
while (a<b)  { blah...  }          // For as long as a is less than b, continue to execute whatever is inside the {} brackets.
for (int n=0 ; n<50 ; n=n+1 ) {..} // This will execute whatever is in the curly brackets, 50 times. Also n will go from 0 to 49.

Useful libraries to include in your code. Many of the commands below rely on these:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/timeb.h>
#include <time.h>

Declaring Variables (for next section)

int i;                                  // Declare an integer
char c;                                 // Declare a char (one character string).
char mystring[100];                     // Declare string of 100 chars big  (but use the malloc method instead for super-large arrays). This is the way to get a string in c.
char x[20][100];                        // Declare 20 strings of 100 length (but use the malloc method instead for super-large arrays or if you want to pass to a function)
struct newtype { int o;	char p[5]; };   // Create a new 'structure' to contain sub-variables (similar to an object in an object-orienated language like Java). In this example, each variable of type "newtype" will contain the subvariables including: an integer - "o", and an array of chars - "p". All structs must be above (and outside) any functions.
newtype ntype;                          // Declare a variable of type newtype. This goes into a function (eg. main() ).

Many of the commands below rely on the variables as declared above, and should go into a function (eg: main() ):

printf("hello\nworld");          // Prints stuff ("\n" means newline)
printf("%s",mystring);           // Prints char array (mystring var)
printf("%c",mystring[99]);       // Print last char the string declared above
printf("%s",x[19]);              // Print last string from the string array (declared above under title "Declaring Variables").
printf("%c",x[19][99]);          // Print last char from the last string in the string array.
mystring[99] = 'z'               // Change last character in mystring string to 'z'
mystring = "hello"               // Obvious, but illegal! You can't directly assign a string to a char array. Use strcpy instead.
x[19][99]    = 'y'               // Change last character in last string to 'y'
strcpy(mystring, "hello");       // Copy "test" to the "mystring" string as declared earlier.
strcpy(x[5], "hello");           // Copy "test" to the 5th string in "x" as declared earlier.
strncpy(x[5], "hello", 5);       // Use strcpy instead usually. This is used if you want to define the number of chars to copy.
strncpy(x[5], mystring+10, 50);  // Takes a substring of mystring (start from 10th char and do 50 of them), and puts it into the x[5] string.
strcat(mystring,"hello");        // Concatenate (add/append) "test" to the string, along with the escape code '\0' to signify the end
strcmp(a,b);                     // Compare two strings. Returns zero if same, -1 if a is less than b, and 1 if a is more than b.
strcmpi(a,b);                    // Case sensitive version of above
strlen(mystring);                // Number of chars so far stored in the string (everything up to escape code '\0')
i = '7'-48;                      // Convert char to int, providing the char is a number from 0-9.
i = 'a';                         // Convert char to int code
c = 7 +48;                       // Convert int to char, providing the number is from 0-9.
c = 97;                          // Convert int code to char ('a' in this case).
i = atoi("456");                 // Convert string to int. Use 'atof' to convert string to double, and 'atol' for converting string to long.
sprintf(mystring, "%d", 123);    // Convert int to string
itoa(123, mystring, 10);         // Convert int to string base 10
i = sizeof(mystring);            // Find (full) length of array (returns 100 in this case)
srand( (unsigned)time( NULL ) ); // Randomize seed
100 *       rand()/(RAND_MAX+1)  // Compute random integer number between 0 and 100  (0 <= r < 100).
68 * rand()/(RAND_MAX+1) + 32    // Compute random integer number between 32 and 100  (32 <= r < 100).
(float)     rand()/(RAND_MAX+1)  // Compute random number between 0 and 1  (0 <= r < 1).
100*(float) rand()/(RAND_MAX+1)  // Compute random floating number between 0 to 99.999... inclusive   (0 <= r < 100).
scanf("%i", &i);                 // Read from input into int i
exit(0);                         // Quit program
system("PAUSE");                 // Pause (Windows only)
char mystring2[]="hello";        // Declare and initialize string in one go
int i2=99;                       // Declare and initialize an integer in one go
ntype.o = 37;                    // Assign the number 37 to the 'o' part of the ntype variable.
ntype.p[3] = 'z';                // Assign the char 'z' to the 3rd element of the array in the 'p' part of the ntype variable.

Arrays, malloc, passing to functions etc.:

int  i = 5;        // Create an integer
char j = 'z';      // Create a character
int  ia[10];       // Create an integer array
char*mystring = (char*)malloc(100000*sizeof(char));           // Create a char array, mystring, of size 100000. Use instead of "char mystring[100000];" for large values like 100000
char**x = (char**)malloc(2000*sizeof(char*));    for (int n=0 ; n<2000 ; n++) { x[n]=(char*)malloc(1000*sizeof(char));  }    // Declare 2000 strings of 1000 length. Use instead of "char x[2000][1000];" for large values, or if you want to pass to a function.
char**x = (char**)malloc(2000*sizeof(char*));    for (int n=0 ; n<2000 ; n++) { x[n]=(char*)calloc(1000,sizeof(char));  }    // Like above, except all are initialized to null.
struct newtype { int amount;   char strings[10][10];   };     // Similar to an object in Java, create a new 'structure' to contain sub-variables. Each variable of type "newtype" will contain an integer - "amount", and a 2D array of chars - "strings". All structs must be above (and outside) any functions.
newtype ntype;              // Using the struct created above, we have created a variable of type 'newtype'.
newtype ntypeArray[10];     // Using the struct created above, we have created a variable array of type 'newtype'.

int z = addtwo(5);                                // Passing the number 5 to the addtwo function which exists below.
int addtwo(int x) { int n=x+2 ; return n ; }      // 5 is put into the function, and it churns out 5+2. Then z above, becomes 7 as a result. The int in 'int addtwo(' simply means that the type to churn out is an integer.

func(i,j);                                        // How to pass a copy of the integer i and j to a function.
void func(int i, char j)   { i=5 ; int i2 = i; }  // How to receive the variables from the function caller. Changing i or j in the {..} does not change the i and j outside the function. 'void' means that nothing is returned to the caller.

func2(&i);                                        // How to pass to the function, a reference to the integer i (instead of a copy). So actual changes to i inside the function affect i globally.
void func2(int *i)   { *i=5 ; int i2 = *i; }      // How to receive a pass from &i. {..} bits show how to use *i.

func3(ia);                                        // Pass the integer array to a function.  By default, arrays are passed by reference.
void func3(int *x) { x[5]=99; }                   // Changes the 5th element of x (or ia too outside the function).

func4(mystring,x);                                // How to pass the 'malloced' variables to a function. By default, arrays are passed by reference.
void func4(char* data, char** data2)   { data[99]=5; data2[99][99]=5;  }              // The function header may look like this. Unlike normal variables, arrays can't be directly copied in C. Therefore in this case, the data variable is actually really the mystring variable, and data2 is actually x.

free(x);                                                 // Use to free a "malloc'ed" array.

func5(ntype);                                            // Pass the ntype variable (type newtype) to the func5 function.
void func5(newtype in) { in.strings[3][3]='z'; }         // Take the passed variable, create a copy of it, and inside the curly brackets, get the "strings" variable part of the newtype, and change one of its chars.

void func6(newtype *in) { (*in).strings[3][3]='z'; }     // Like func5, but access the variable directly - don't make a copy.

func7(ntypeArray);                                       // Pass a "newtype" array to func7.
void func7(newtype *in) { in[5].strings[3][3]='z'; }     // Just like when passing normal arrays (like int and char), by default, they are passed by reference.

File opening, saving, etc.:

FILE *fs = fopen("output.txt", "w");             // Create file for writing. Use "a" instead of "w" for append instead.
fwrite(mystring, 1, sizeof(string), fs);         // write string to the created file

FILE *fl = fopen("input.txt", "r");              // Input file for reading.
if (!fl) { printf("Cannot open file for reading\n"); exit(0); }                // Check if file exists.
char *array=(char *)malloc(getFileSize(fl));     // Create array of the file's size (the getFileSize() function is a custom function as described below).
fread(array, 1, getFileSize(fl), fl);            // Read file into previously created array.

char ch = fgetc(fl);                             // Read one character from the file and put it into ch.
int getFileSize(FILE* fin)  { fseek(fin,0,2); int size=ftell(fin); rewind(fin); return size; }  // Find filesize function.

Clock test - great for testing the speed of your code

struct timeb timef; ftime (&timef);  long startTime = timef.time * 1000 + timef.millitm;                                           // Start clock
ftime (&timef);	                     long endTime   = timef.time * 1000 + timef.millitm;  printf("Time: %d ms",endTime-startTime); // End clock

Special characters for use in strings

\n	Newline	
\?	Question mark	
\'	Single quote	
\"	Double quote
\t	Horizontal tab
\a	Bell (alert)	
\b	Backspace	
\\	Backslash


  • Frequently Asked Questions on C
  • Eddie's basic guide to C programming
  • C Programming Notes

    Found this site of use, or want to say something? Please email me

    Skytopia > Articles > Quick reference to the most common commands used in C/C++    (article created 05/07/2006)

    This page is copyright 2006 onwards Daniel White.
    If you wish to duplicate any of the information from this page, please contact me for permission.