The Wayback Machine - https://web.archive.org/web/20240623234845/https://www.geeksforgeeks.org/10-cpp-programming-tricks-that-you-should-know/
Open In App

10 C++ Programming Tricks That You Should Know

Last Updated : 17 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

C++ Programming Language is a powerful, versatile, and compiled language, which means the source code is converted into machine language before the execution. In order to make your code as efficient and effective as possible, you should be aware of the following tricks and techniques. Hence, it’s better to know some C++ tricks and tips to reduce a few lines of code. 

C++ Programming Tricks

In this article, you will come across some of the most important C++ tricks you should know in order to build interesting apps. These tips and tricks when applied help in saving time and reducing the code length. Let’s go through each of these tricks which help C++ developers to build amazing apps. 

Tricks for C++ Programming Language

So if you are curious to know about the 10 tricks of the C++ programming language then let’s get started.

1. Avoid Including Multiple Libraries

Generally, we include libraries at the start of the C++ code to perform certain operations as shown below.

Example:

C++
#include <iostream>
#include <set>
#include <string>
#include <vector>
using namespace std;

int main()
{

    cout << "GFG!";
    return 0;
}
#include <iostream>

 This “iostream”  library performs the input-output operations in C++ code.

#include<vector> 

 The “vector” library allows us to perform operations on vectors.

#include<set>

Including this library, we can use operations on sets.

But, we have a better approach to replace these many libraries with just one library i.e, #include bits/stdc++.h> to include all standard libraries without adding them one at a time. It is especially useful in programming competitions where time is limited.

 #include<bits/stdc++.h>

This includes all the standard libraries required in the program. So, we can avoid adding these many libraries separately to keep code as efficient and effective as possible.

2) Globally Defining Statements and Using them Locally Just by Some keywords

Yes, You can replace a statement just with a word by using the global definition in C++ Programming Language. For example, you have to print “GFG” at places in your program and you don’t want to write whole again and again; You can define a word with the same definition to avoid writing the same line multiple times.

cout<<"GFG!"<<endl;

Example 1:

C++
#include <bits/stdc++.h>
using namespace std;
#define gfg cout << "GFG!"<<"\n";
int main() {

    gfg
    gfg
    return 0;
}

Output:

 GFG!
GFG!

Suppose, you’ve to convert all the integer data types into “long long”, so instead of changing each “int” into “long long”, we can simply define int with long long.

Example 2:

C++
// C++ Program to demonstrate use 
// of #define using long long
#include <bits/stdc++.h>

using namespace std;

#define int long long

int32_t main()
{
    int x = 1e12 + 5;
    int y = 1e10;
    cout << x + y << endl;
}

Output
1010000000005

This output as well as these x and y in the program are out of range of integer, but as we defined it earlier, it can now store long long. 

Note: While defining ‘int’ as ‘long long’, we must always keep in mind that the main() function always returns the 32-bit integer, so we have to convert 

int main (){ …} into  int32_t main(){ …}

3. Use Conditional/Ternary Operators

Although conditional operators follow the same algorithm as if-else statements, they take up less space and make it easier to write if-else statements in a shorter manner.

b = ( a ? x : y  ) ==> if a is true then b = x else b = y

In the above statement if a is true then b = x else b = y. It is similar to the below if-else statement.

if(a)
{
b=x;
}
else
{
b=y;
}
Conditional or Ternary operator in C++

Ternary operator

Example:

C++
// C++ Program to Use Conditional/Ternary Operators
#include <bits/stdc++.h>
using namespace std;

int main()
{

    int x = 45;
    int y = 54;
    int z = (x > y) ? x : y;

    cout << "Bigger of the two is " << z << endl;
}

Output
Bigger of the two is 54

4. Using STL (Standard Template Library)

The STL (Standard Template Library) is a collection of Algorithms, Containers, and functions. It’s very useful in programming and it saves so many lines of code just by replacing them with some small code snippet, defined in STL. 

A) Algorithms: In this component, there are various algorithms for searching, and sorting. 

For example, We can use binary search using STL.

Syntax: 

binary_search(startaddress, endaddress, valuetofind);

Return type: It will return True if it finds the value, and False otherwise.

Time Complexity: O(log n)

We can use Sorting in a similar manner.

Syntax: 

sort(startaddress, endaddress); 

Time Complexity: O(n logn)

B) Containers:  Containers are used to store data. There are various types of containers that have unique properties. A few of them are as follows. 

Vector:  A vector is a dynamic array. It can resize itself wherever required. Data is inserted in the end and can be popped out from the back itself. It is used where the data is dynamically passed. 

Syntax: 

vector<dataType> vector_name;

Stack: A stack is a container that works in LIFO (Last In First Out) principle. In stack, a new element is always inserted from the top and popped out from the end. 

Syntax: 

stack<dataType> stack_name;

Queue: Queue is a container that works in FIFO (First In First Out) principle. In queue, a new element is always inserted from the end (Back) and popped out from the front.

Syntax: 

queue<dataType> queue_name;

Other important containers are Set, Multiset, Priority_queue, Deque, Map, Multimap, Unordered map, etc. 

Thus by using STLs, not only do we reduce the lines of code but also we get more convenient data structures to work with. Hence It’s a good practice to use STLs. 

5. Using Bitwise Operations

Bitwise operations are used when we have to operate on bits of a number. Since we operate on bits, it helps us operate on large numbers easily. Bitwise operations are very useful in programming. A few of the best use cases of Bitwise operations are as follows: 

Checking odd numbers

We can check if a number is odd or even just by taking & ( bitwise and) of the number with 1. 

if(num & 1)
{
cout<<"Number is odd"<<endl;
}
else
{
cout<<"Number is even"<<endl;
}

Using Left and Right Shift Operator

The left shift operator is used to multiply a number by 2 and the right shift operator is used to divide a number by 2 efficiently ( very useful in case of huge numbers).

Example:

C++
// C++ Program to demonstrate use 
// of Left shift and Right Shift
#include <iostream>
using namespace std;

int main()
{

    int x = 18;
    cout << "x << 1 = " << (x << 1) << endl; // left shift
    cout << "x >> 1 = " << (x >> 1) << endl; // right shift
    return 0;
}

Output
x << 1 = 36
x >> 1 = 9

Check if a number is a power of 2 or not. 

Yes, this can be checked by using bitwise and operator. If a number is a power of 2, then it must have only one set bit in its binary representation. So,  if we subtract 1 from this number it’ll have all set bits except the one which was set previously. Hence, we take bitwise and of number and (number-1). If this value returns zero, then the number is a power of two, otherwise, it’s not.

Example:

C++
// C++ program to check if a
// number is power of 2 or not
#include <bits/stdc++.h>
using namespace std;

bool isPowerOfTwo(int x) { return x && (!(x & (x - 1))); }

// Driver code
int main()
{
    if (isPowerOfTwo(32))
        cout << "Yes\n";
    else
        cout << "No\n";
    if (isPowerOfTwo(31))
        cout << "Yes\n";
    else
        cout << "No\n";
    return 0;
}

Output
Yes
No

Swapping Two Variables without the third variable

The bitwise XOR operator can be used to swap two variables. The XOR of two numbers x and y returns a number that has all the bits as 1 wherever bits of x and y differ. 

Example:

C++
// C++ Program to swap two variables
// without the use of third variable
#include <iostream>
using namespace std;

int main()
{

    int x = 10;
    int y = 20;

    cout << "Before Swap X: " << x << " Y: " << y << endl;

    x ^= y;
    y ^= x;
    x ^= y;

    cout << "After Swap X: " << x << " Y: " << y << endl;

    return 0;
}

Output
Before Swap X: 10 Y: 20
After Swap X: 20 Y: 10

Time Complexity: O(1)
Auxiliary Space: O(1)

6. Using the ‘auto’ keyword to Drop Data Type

A) Instead of using int, string, or char data type, we can simply write auto for variable declaration.

Example:

int a = 21;
char c = 'z';
string s= "GFG";
float x = 45.5;

Can be declared as : 

auto  a = 21;
auto c = 'z';
auto s= "GFG";
auto x = 45.5;

B) For traversing, instead of using for loop syntax we can use the ‘auto’ keyword.

Example:

//Generally for loop is used as -
for(int i=0;i< v.size() ;i++)
{
//traversal
}

// But this can be simply written as-
for ( auto i: v){

7. Finding the Number of Digits in a Number

In a positive number, if we have to find the number of digits, we can do it with the help of log(10) (Logarithm with base 10).

Digit count of N = floor log10(number) 

Example:

C++
// C++ Program to find the number of digits in a number
#include <bits/stdc++.h>
using namespace std;

int Digit(long long n) { return floor(log10(n) + 1); }

int main(void)
{
    long long n = 9878946457;
    cout << "Number of digits : " << Digit(n);
    return 0;
}

Output
Number of digits : 10

8. Using the in-built GCD function

In many competitive programming problems, we get questions where we have to calculate the GCD (Greatest Common Divisor). So, it’s better to use the in-built function of GCD rather than writing Euclid’s theorem.   

Syntax: 

__gcd(num1, num2);

Returns: It returns 0 when both num1 and num2 are zero otherwise, it returns gcd of num1 & num2.

9. Use of “or” and “and”

When writing C++ code, “and” and “or” can help improve readability instead of & and |. Though this habit is not very productive but will help to use conditional operators easily.

Example:

C++
// C++ Program to demonstrate use of or 
#include <iostream>
using namespace std;

int main()
{

    int x = 10;
    if (x < 11 or x > 0) {
        cout << "YES" << endl;
    }
    else {
        cout << "NO" << endl;
    }
    return 0;
}

Output
YES

10. Using Pre-Increment Instead Post-Increment

Instead of using post-Increment, we should use pre-Increment as it is more efficient. Pre-Increment requires only one operation whereas post-Increment requires Two operations and keeps a copy of the previous operation. It is possible to use pre-increment both as an expression and as a statement, providing greater code flexibility. 

++i; // faster than post-increment

These were some important tricks of the C++ programming language. One can follow these tricks to make their code clean, crisp, and short, and can save time in the contests by avoiding writing whole algorithms where it’s not needed.

Conclusion

Programming in C++ is the most required skill that big tech companies look after. Now that you know about the most important C++ tricks used in programming, you can explore each and use them accordingly wherever required. These C++ tricks will help in reducing the number of lines in code and thus you can implement a fully-functional app with less complexity. 

Related Articles:



Similar Reads

13 Things You Should Know Before You Enter In Web Development
Every beginner starts their journey in web development learning frontend part, backend part, and some tools which are important to build the web project. Building your first project on your own after so many struggles is an exciting feeling for the beginners. You start having a lot of expectations from your job but when you enter the industry you f
7 min read
10 Secret AI Websites You Should Know (But No One Told You About)
If you're looking around you, people now started using AI websites and apps. It's true that the AI era has started and boomed since the launch of ChatGPT. So, are you using AI to boost your performance? If not, how does it feel living under the rock? With so many great things on the table, we often miss out on the best ones. Well, that’s the same c
10 min read
10 JavaScript DOM Tips and Tricks That Every Developer Should Know
The DOM stands for ‘Document Object Model’, it’s a programming interface for HTML (Hypertext Markup Language) and XML (Extensible Markup Language) documents. DOM represents the structure of a document which means a hierarchical tree-like structure, where each existing element in the document are represented as a node in the tree. It also provides p
13 min read
CSS Tricks That Every Web Developer Should Know
CSS (Cascading Style Sheets) is the magic ingredient that breathes life into the raw structure of HTML, transforming it into visually captivating and user-friendly interfaces. While the core concepts of CSS are relatively easy to grasp, mastering its nuances takes dedication and practice. But the rewards are substantial. With CSS proficiency, you g
7 min read
7 VS Code Tricks That You Must Know
VS Code Tricks are in reality those powerful tools or you may also say the features which the developers may confidently load in their pockets. From constructing the VS Snippets individually to helping you while speedily navigating the multiple VB files, it is possible to do such things via these dynamic VS Code Tricks. However, it isn’t vital to r
7 min read
Top 10 Kubernetes Tricks You Didn't Know
Kubernetes is a popular tool for building and running applications in the cloud. Kubernetes provides a stable framework for managing containerized applications. The simple and stable features of this framework have made it a leader in container orchestration. Many of the senior developers also are not aware of some less-known Kubernetes features. M
9 min read
10 Python In-Built Functions You Should Know
Python is one of the most lucrative programming languages. According to research, there were approximately 10 million Python developers in 2020 worldwide and the count is increasing day by day. It provides ease in building a plethora of applications, web development processes, and a lot more. When it comes to making a program short and clear, we us
5 min read
10 Things You Should Know As a Web Developer
Writing a thousand lines of code and turning that into a website is one of the most creative and complicated things for web developers. If you get excited seeing a lot of beautiful websites and thinking to try your hands on them then we need to open your eyes by telling you some important things that you should know as a web developer. Creating a w
8 min read
10 Web Development and Web Design Facts That You Should Know
Web Development has grabbed a lot of attention in today's date. But the question arises, why has it gained such a massive audience in the last decade. So Here's the answer: Web development is the basic building and maintenance of websites; it’s the whole procedure that happens to make a website look great, responsive, work smooth, and performing we
6 min read
How Much Python Should You know To Learn Django?
How much python is required to learn Django?? This question comes to the mind of every beginner and experienced developer who wants to learn Django and build an application in it. No doubt most developers or beginner wants to learn any framework or library as soon as possible. We all want to know the minimum prerequisite that is needed to learn any
6 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg