Programming Tips in C


This website is designed to be a central place to link to a huge variety of tips and tricks in the C programming language to make your life a little easier as you write programs in such a minimalistic language.


Understand that this website is targeted at GCC in Linux, so most of the tips will work elsewhere, but some may not.


Timer - Timing and displaying how long a piece of code took to run

Comment out blocks of code - Make it clear why you're not using it anymore

Macro Tips - General things to watch out for while using Macros

Factorial - Why NOT to calculate factorials

Powx - Quick exponentiation function

Saturated Addition - When addition overflows, keep it at 0xFFFFFFFF.

FNV Hash - A simple routine to hash large amounts of data

Seeding rand() - How to seed the random number generator so it gives different results each time

String Handling

Check if two strings are equal

Stringize Preprocessor Arguments - How to insert an argument to a macro in a string

Text Editing - Never write a text editor, use one from the environment

Display Time - How to display a length of time so it's easier to read than a huge number of seconds

Temporary Return Buffer - A leak proof way to return char * without malloc/free

Data Structures

Intro to bitwise operations - Basic intro to the different ways to use bitwise operations

Count Bits - How to quickly count the number of bits set in an unsigned int

Binary Constants - Macros to let you use binary contants straight in your code

Digit Mask - Simple macro to pull out one digit of a number

Bit Manipulation - How to set, flip, or test individual bits

Coordinate compression - Use macros to turn multidimensional array coordinates into one int


Debug Messages - Using the preprocessor to compile in debugging messages only if you want them

Assert - A good way to make a sanity check and have the program throw up if something is seriously wrong

#error - Create your own compile errors

GDB - Quick and dirty intro to using the GNU DeBugger 


Miscelaneous Tips - Tips that don't warrent an entire page and links to other good sites


Prime Generator - Piece of code that generates the next prime number when you call it and returns it as a uint64_t.

Fibonacci Generator - Simple function that will always return the next number in the Fibonacci sequence.

Practice Problems


Since this is a wiki, that means you can help add to this website too.  If you would like to help contribute to this collection of tricks, simply email Kenneth Finnegan and ask to be invited as a writer.  Even if you don't want to be a writer, but just have another trick or link to share, feel free to email Kenneth.