Coding Tips and Tricks

Blog

C Programming Tips and Tricks Every Programmer Should Know

Top C Programming Tips and Tricks.
Top C Programming Tips and Tricks.

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 to the size of its field.

#define NUM_OF(x) (sizeof (x) / sizeof (*x))

Tip#2) – Calculate Elapsed Time

Friends, have you ever needed to calculate the time passed between two events? Or keep a check on some function which is spuriously taking extra execution time than expected?

Here is the code snippet implemented using a set of macros to help you figure out how long something will take to run.

Tip#3) – Smart Random Number Generator

We have this rand() function defined in the stdlib.h for the random number generation. Did you use it and realized that every time you run your program, but 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.

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 “goes to” operator works, go through the below code snippet.

In the example, there is conditional’s code which decrements variable x, while returning x’s original (not decremented) value, and then compares it with 0 using the > operator.

Tip#5) – Some Cool SCANF Tricks

Find out some of the unheard scanf tricks that you must know.

Tip#6) – Call Functions at Program Termination

Did you know about the atexit() API? This C API is used to register functions which can get automatically called when the program finishes its execution.

For example –

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 into a file and then store the file content into the 2-D array with the following line of code.

Tip#8) – Add Any Numbers without “+” Operator

Bitwise operators can be used to perform the addition (+) operation as mentioned in below example:

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.

Tip#10) – Put the Constant As the First Term While Making Comparisons

Sometimes, we tend to confuse “=” operator with “==” 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.

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

can be miss written as

Tip#11) – Quick Commenting

Sometimes you may find yourself trying to comment blocks of code which have comments within them. Because C does not allow nested comments, you may find that the */ comment end is prematurely terminating your comment block.

You can utilize the C Preprocessor’s #if directive to circumvent this:

Tip#12) – Use of Conditional Operator

The Conditional operator is also known as the Ternary operator. We mostly use it in the following form:

But in C++, you can also use it in the following manner:

Tip#13) – Arrays and Pointers not Entirely the Same

Many of us tend to misunderstand a 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 which can hold only values of 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.

Tip#14) – Pointer to array and Array of Pointers

Let’s check out an interesting comparison between the following three declarations.

Here in int *ptr1[5], ptr1 is an array of 5 integer pointers (An array of int pointers).

And in int (*ptr2)[5], ptr2 is a pointer to an array of 5 integers (A pointer to an array of integers).

It’s same as ptr1 (An array of int pointers).

Video

Getting Started

Open the Welcome page to get started with the basics of VS Code. Help > Welcome.

Includes the Interactive Playground.

Add JSON Validation

Enabled by default for many files. Create your own schema and validation in settings.json

or for a schema defined in your workspace

or a custom schema

See more in the documentation.

Very fast random number generator

Xorshift random number generators can be used to create sequences of pseudorandom numbers very, very quickly. They are useful when you need randomness but don't want to suffer a performance penalty.

Here is an implementation taken from Aristide on StackOverflow:

Whether a number is divisible by another number

If you want to know if 10 is divisible by 2, you can use the modulo operator to find out the remainder when you divide 10 by 2. If it's , the number is divisible by that number.

This is how you can solve the FizzBuzz problem.

Status Bar

Errors and warnings

Keyboard Shortcut: ⇧⌘M (Windows, Linux Ctrl+Shift+M)

Quickly jump to errors and warnings in the project.

Cycle through errors with F8 or ⇧F8 (Windows, Linux Shift+F8)

You can filter problems either by type ('errors',

You can filter problems either by type (‘errors’, ‘warnings’) or text matching.

Change language mode

Keyboard Shortcut: ⌘K M (Windows, Linux Ctrl+K M)

If you want to persist the new language mode for t

If you want to persist the new language mode for that file type, you can use the Configure File Association for command to associate the current file extension with an installed language.

Snippets

Create custom snippets

File > Preferences > User Snippets (Code > Preferences > User Snippets on macOS), select the language, and create a snippet.

See more details in Creating your own Snippets.

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 in delivering 15 wonderful tips.

We tried to cover those tips which you can relate to and 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 @ his wiki page.

Before we conclude, a humble request 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 the C/C++ programming.

Recommended Posts:

Tags