TechBeamersTechBeamers
  • Python
    • Python Basic
    • Python OOP
    • Python Quiz
    • Python Examples
    • Python Interview
    • Python Selenium
    • Python Advanced
  • Java
    • Java Quiz
    • Java Interview
  • C
  • C#
  • SQL
  • MySQL
  • Selenium
    • Selenium Tutorial
    • TestNG Tutorials
    • Selenium Interview
    • Selenium Quiz
  • Testing
    • Software Testing
    • Manual Testing
    • Software Testing Quiz
    • Testing Interview Questions
  • Agile
  • More
    • Bookmarks
    • Customize
    • About Us
    • Contact
Search
More Tutorials
  • Agile Tutorial
  • Android Tutorial
  • Angular Tutorial
  • Linux Tutorial
  • TestNG Tutorial
Interview Q&A
  • Python Questions
  • Java Questions
  • PHP Questions
  • Web Dev Questions
  • Linux Questions
Coding Quizzes
  • Python Quiz
  • Java Quiz
  • Selenium Quiz
  • HTML CSS Quiz
  • Shell Script Quiz
ยฉ 2023 TechBeamers. All Rights Reserved.
Reading: C Programming Tips and Tricks for Beginners โ€“ Top 15
Share
Notification Show More
Aa
TechBeamersTechBeamers
Aa
  • Agile
  • Android
  • Angular
  • Best IDEs
  • C
  • C#
  • CPP
  • HTML
  • IOT
  • Java
  • Java Interview
  • Java Quiz
  • Linux
  • MySQL
  • PHP Interview
  • Python
  • Python Basic
  • Python Quiz
  • Python Examples
  • Python Advanced
  • Python Interview
  • Python OOP
  • Python Selenium
  • QA Interview
  • Selenium
  • Selenium Quiz
  • Selenium Interview
  • Shell Script Quiz
  • Software Testing
  • Software Testing Quiz
  • SQL Interview
  • Web Development
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Java Interview
    • C# Interview
    • PHP Interview
    • Python Interview
    • QA Interview
    • Selenium Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quiz
    • Java Quiz
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • ShellScript Quiz
    • C/C++ Quiz
  • Bookmarks
    • My Bookmarks
    • My Interests
Follow US
ยฉ 2023 TechBeamers. All Rights Reserved.
TechBeamers > Blog > Linux Tutorials > C Programming Tips and Tricks for Beginners โ€“ Top 15
Linux Tutorials

C Programming Tips and Tricks for Beginners โ€“ Top 15

Last updated: 2023/05/22 at 12:58 PM
By Harsh S.
Share
13 Min Read
SHARE

Weโ€™ve assembled 15 cool C Programming Tips and Tricks in this article.

Contents
C Programming Tips and Tricks Every Programmer Should KnowTip#1) โ€“ Macro to Get Array Size of Any Data TypeTip#2) โ€“ย Calculate Elapsed TimeTip#3) โ€“ย Smart Random Number GeneratorTip#4) โ€“ย Heard of โ€œgoes to-->โ€ Operator?Tip#5) โ€“ย Some Cool SCANF TricksTip#6) โ€“ย Call Functions atย Program TerminationTip#7) โ€“ย Initialize a 2-D Array with aย Long List of ValuesTip#8) โ€“ย Add Any Numbers without โ€œ+โ€ย OperatorTip#9) โ€“ย Swapping Two Variables without Any Temp VariableTip#10) โ€“ย Put the Constant As the First Term While Making ComparisonsTip#11) โ€“ Quick Comment Your CodeTip#12) โ€“ย Use of Conditional OperatorTip#13) โ€“ย Arrays and Pointers not Entirely the SameTip#14) โ€“ย Pointer to array and Array of Pointers.Tip#15) โ€“ Log off the computer Using C.Summary โ€“ C Programming Tips and TricksRecommended Posts:

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

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 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.

Recommended Posts:

  • C Programming Tutorials for Beginners
  • C/C++ Programming Test for Beginners
  • GDB Tips for Beginners

You Might Also Like

7 Essential Linux Commands Helpful for Programmers

20 Shell Scripting Questions for Practice

Python Tips and Tricks: Unlocking the Hidden Techniques

Must Know Linux Interview Questions

Basic Linux Questions and Answers โ€“ Online Test for Freshers

TAGGED: best coding tips, c/c++ programming tips

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
Loading
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Share This Article
Facebook Twitter LinkedIn Email Copy Link
Share
By Harsh S.
Seasoned IT specialist, thinker, creator and coffee lover. Years of experience in programming languages like C, C++, C#, Objective-C, PHP, HTML/JavaScript, Angular JS, Java/J2EE, Python, Selenium. Excelled in using technologies like CI/CD with Jenkins, AWS, VMWare, EXSI, Virtual Box and a no. of Unix/Windows/Android platforms.
Previous Article Ant script to change system date and time on Windows and Linux. Ant Script to Change System Date-Time โ€“ Win/Linux/Mac OS
Next Article How to use eval command in Unix Unix Powerful Command โ€“ Eval
4 Comments 4 Comments
  • Meenakshi Agarwal says:
    May 25, 2017 at 12:44 am

    Glad to hear that our tips were helpful for you. Thanks.

  • Mark says:
    May 24, 2017 at 1:44 am

    This is very helpful! Iโ€™ve seen some of these tricks in code before but never understood them. Thank you very much!

  • Harsh S. says:
    August 13, 2015 at 9:14 pm

    Thanks Meenakshi.

  • meenakshi404 says:
    August 13, 2015 at 7:46 pm

    Very nice collection of C programming tips, itโ€™s hard to find such useful tips at one place. Good work!

Leave a Reply

Your email address will not be published. Required fields are marked *

Latest Tutorials

Learn how to do factorial in python
Factorial Program in Python with Examples
Python Examples June 9, 2023
4 ways to find all possible string permutation in Python
Find All Possible Permutation of a String in Python
Python Examples April 30, 2023
SQL Exercises with Sample Table and Demo Data
SQL Exercises โ€“ Complex Queries
SQL Interview May 10, 2020
//

From Python to Java and everything in between, weโ€™ve got you covered with practical and actionable advice designed to help you level up your coding skills.

Quick Link

  • MY BOOKMARKS
  • MY INTERESTSNew
  • CONTACT US
  • BLOG INDEX

Top Categories

  • AGILE
  • BEST IDEsHot
  • PYTHON
  • SQL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
ยฉ 2023 TechBeamers. All Rights Reserved.
  • Contact Page
  • About Us
  • Terms of Use
  • Privacy Policy
  • Disclaimer
Join Us!

Subscribe to our newsletter and never miss our latest news, podcasts etc..

Loading
Zero spam, Unsubscribe at any time.