Weโve assembled 15 cool C Programming Tips and Tricks in this article.
If you are a โCโ learning student or a โCโ programmer, then these tips are for you andย can come quite handy in yourย work assignments.
We discovered some of these ideas after lots of reading and some while working. And all of our tips are based on real-time use cases that will help you solve real-time issues.
If you also have a few ideas in store, then donโt mind sharing them with us. Use the comment box section and let others know as well.
Also, you can participate in our knowledge drive by distributing this post to your social circle and friendย groups.
Letโs now start looking intoย the tips one by one.
C Programming Tips and Tricks Every Programmer Should Know

Tip#1) โ Macro to Get Array Size of Any Data Type
The following macro will help you in getting the size of an array of any data type. ย It works by dividing the length of the array by the size of its field.
#define NUM_OF(x) (sizeof (x) / sizeof (*x))
#define num(x) (sizeof (x) / sizeof (*x))
int _tmain(){
int number[10] = {1,1,1,1,1,1};
char *teststr[20] = {"","","","","","","","",""};
printf("Size of number[10] is %d\n", num(number));
printf("Size of teststr[20] is %d\n", num(teststr));
}
Size of number[10] is 10
Size of teststr[20] is 20
Press any key to continue . . .
Tip#2) โย Calculate Elapsed Time
Friends, have you ever found yourself in a situation where you needed to measure the time span between two occurrences? Or monitor a process that is unexpectedly consuming more time than anticipated?
Here is theย code snippet implemented using a set of macros to help you figure out how long something will take to run.
#include "stdafx.h"
#include <time.h>
#include <windows.h>
#include <stdlib.h>
clock_t startm, stopm;
#define BEGIN if ( (startm = clock()) == -1) \
{ \
printf("clock returned error.");exit(1); \
} \
#define CLOSE if ( (stopm = clock()) == -1) \
{printf("clock returned error."); \
exit(1); \
} \
#define SHOWTIME printf( "%6.3f seconds elapsed.", ((double)stopm-startm)/CLOCKS_PER_SEC);
main() {
BEGIN;
// Specify set of instructions for you want to measure execution time
Sleep(10);
CLOSE;
SHOWTIME;
}
Tip#3) โย Smart Random Number Generator
In C programming, the stdlib.hย header provides the rand() function for generating numbers. Did you use it and realized that every time you run your program, it returns the same result?
Itโs because, by default, the standard (pseudo) random number generator gets seeded with the number 1. To have it start anywhere else in the series, call the function srand (unsigned int seed).
For the seed, you can use the current time in seconds.
#include <time.h>
// At the beginning of main, or at least before you use rand()
srand(time(NULL));
Annexure:
For your note, the above code seeds the generator from the current second of time. Thisย fact implies that if you expect your program to re-run more than once a second, the given code may not fulfill your requirement. A possible workaround is to store the seed in a file (thatย you will read later from your program), andย you then increment it every time the program is run.
Tip#4) โย Heard of โgoes to-->
โ Operator?
In C programming, the symbol (โ>) doesnโt represent an operator.
Instead, it is a combination of two separate operators, i.e., --ย
and >
known as the โgoes to.โ
To understand how the โgoes toโ operator works, go through the below code snippet.
In the example, there is conditionalโs code that decrements variable x, while returning xโs original (not decremented) value, and then compares it with 0 using the > operator.
int _tmain(){
int x = 10;
while( x --> 0 ) // x goes to 0
{
printf("%d ", x);
}
printf("\n");
}
9 8 7 6 5 4 3 2 1 0
Press any key to continue . . .
Tip#5) โย Some Cool SCANF Tricks
Find out some of the unheard scanf() tricks that you must know.
scanf(โ%[^,]โ, a); // This doesnโt scrap the comma
scanf(โ%[^,],โ,a); // This one scraps the comma
scanf(โ%[^\n]\nโ, a); // It will read until you meet โ\nโ, then trashes the โ\nโ
scanf(โ%*s %sโ, last_name); // last_name is a variable
Tip#6) โย Call Functions atย Program Termination
Did you know about the atexit() API? This C API is used to register functions that can get automatically called when the program finishes its execution.
For example โ
#include <stdio.h>
#include <stdlib.h>
void foo(void)
{
printf("Goodbye Foo!\n");
}
void bar(void)
{
printf("Goodbye Bar!\n");
}
int main(int argc, wchar_t* argv[])
{
atexit(bar);
atexit(foo);
return 0;
}
Notice that foo and bar functions havenโt been called but are registered to get called when the program exits.
These should not return anything nor accept any arguments. You can register up to 32 such functions. Theyโll get called in the LIFO order.
Tip#7) โย Initialize a 2-D Array with aย Long List of Values
It can be easily achieved by keeping the list values in a file and then storing the file content in the 2-D array with the following line of code.
double array[SIZE][SIZE] = {
#include "float_values.txt"
}
Tip#8) โย Add Any Numbers without โ+โย Operator
Bitwise operators can be used to perform the addition (+) operation as shown in below C code:
int Add(int x, int y)
{
if (y == 0)
return x;
else
return Add( x ^ y, (x & y) << 1);
}
Tip#9) โย Swapping Two Variables without Any Temp Variable
There are three ways to do this which Iโve mentioned below.
To swap two variables without using additional space or arithmetic operators, you can simply use the xor operator.
a = a ^ b;
b = a ^ b;
a = a ^ b;
// OR
a = a + b โ(b=a);
// OR
a ^= b ^= a ^= b;
Tip#10) โย Put the Constant As the First Term While Making Comparisons
Sometimes, we tend to confuse the โ=โ operator with the โ==โ operator. To avoid this, use the defensive programming approach. 0==x instead of x==0 so that 0=x can be caught by
It means you should write โ1==xโ instead of โx==1โ so that the compiler will always flag an error for the miswritten โ1=xโ.
So whenever you mistakenly write the following.
if ( 1ย = x )
The compiler will complain and refuse to compile the program.
While itโs not possible if you are comparing two variables. For example, the expression
if (x == y)
can be miss written as
if(x = y)
Tip#11) โ Quick Comment Your Code
Sometimes you may find yourself trying to comment out a block of code that already has some comments inside. Because C does not allow nested comments, you may find that the */ comment end prematurely terminating your comment block.
You can utilize the C Preprocessorโs #if directive to circumvent this:
#if 0
/* This code here is the stuff we want commented */
if (a != 0) {
b = 0;
}
#endif
Tip#12) โย Use of Conditional Operator
The Conditional operator is also known as the Ternary operator. We mostly use it in the following form:
x = (y < 0) ? 10 : 20;
But in C++, you can also use it in the following manner:
(c < 0 ? a : b) = 1;
// If c < 0 then a = 1
// If c > 0 then b = 1
Tip#13) โย Arrays and Pointers not Entirely the Same
Many of us tend to misunderstand the concept that pointers and arrays are the same. They are not.
Pointers are merely variables holding the address of some location whereas an array is a contiguous sequence of memory locations.
Pointers can help to create heterogeneous data structures such as a link list or hash table. Whereas the arrays are homogenous and can hold only values of a similar type such as numbers and strings.
Pointers get allocated dynamically on the heap whereas the arrays are static allocations on the stack.
At compile time, an array is an array. Only during run-time, an array devolves to a pointer.
To prove this fact, let me show you an example.
int a[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int *b = a;
printf("%d\n%d\n", sizeof(a), sizeof(b));
And the output is (assuming size of int is 4 bytes and address size is 8 bytes) โ
40
8
Tip#14) โย Pointer to array and Array of Pointers.
Letโs check out an interesting comparison between the following three declarations.
int *ptr1[5];
int (*ptr2)[5];
int* (ptr3[5])
int *ptr1[5];
Here in int *ptr1[5], ptr1 is an array of 5 integer pointers (An array of int pointers).
int (*ptr2)[5];
And in int (*ptr2)[5], ptr2 is a pointer to an array of 5 integers (A pointer to an array of integers).
int* (ptr3[5]);
Itโs the same as ptr1 (An array of int pointers).
Tip#15) โ Log off the computer Using C.
#include <windows.h>
int main(){
system("shutdown -l -f -t 00");
}
Summary โ C Programming Tips and Tricks
While starting to write this article, we thought to present you with ten best of the C programming tips but ended up delivering 15 wonderful tips.
We tried to cover those tips which you can relate to and that are usable in your production environment. For your information, weโre deeply inspired by the father of C โDennis Ritchie.โ You can also follow him on his Wiki page.
Before we conclude, a humbly request you to share this post with your friends. And also leave your valuable feedback in the comment box at the end of this post.
Youย are most welcome to ask questions about this postย which weโll be more than happy to answer.
However, below are some tutorials and posts which we recommend for you to read and build a better understanding of C/C++ programming.
Glad to hear that our tips were helpful for you. Thanks.
This is very helpful! Iโve seen some of these tricks in code before but never understood them. Thank you very much!
Thanks Meenakshi.
Very nice collection of C programming tips, itโs hard to find such useful tips at one place. Good work!