Open In App

Custom C++ User Snippet in Visual Studio Code

Snippets are the small portion of re-usable code wrapped in some prefix word, It allows programmers to bind a particular block of code in a single prefix keyword. Visual Studio Code is a Lightweight and powerful source code editor available in Windows, Linux, and macOS, It comes with many built-in snippets for the loops, control statements, and some keywords. But you know, we can also create our own custom code snippets for time saving and avoiding writing the same piece of code again and again. Users can code faster and productively with the help of custom code snippets.

Existing Snippet in VS Code

Built-in the snippet for the loop.

Now let’s take a look at how we can create our own code snippets for c++ language.



Steps need to be performed.

Here we were going to create a user snippet for the C++ language header template, In the Windows machine.

Step 1: Open the Visual Studio Code, and go to the ‘Manage’ (Gear icon in the bottom left corner).



Step 2: From opened options, Select the ‘User Snippets’ option.

Step 3: Select your programming language in which you are going to create a snippet. (Here we are selecting C++).

Step 4: Now, one cpp.json file will open Where we have to write a code for our code snippet. First, un-comment the code present below their instructions. (refer to screenshot).

Step 5: In this step, we have to do appropriate changes to their code.

First, Let’s understand the meaning of terms present in the code. Snippets generally have four main properties.

  1. Print to console: This is the word, which will open our snippet when we call it.
  2. Prefix: This prefix is used when selecting the snippet in intellisense.
  3. Body: In the body we are writing our main snippet code.
  4. Description: In this we have to mention brief description of snippet for our reference only.

Note – 

Our C++ Template Code Snippet

In our snippet, we have used a ‘boilerplate‘ as ‘print to console’, which means when we type boilerplate and press Enter, our snippet is executed.

Prefix gave as ‘boilerplate code’. This will visible while typing the name of the snippet.

The prefix is visible while writing snippet name

In the body, we have included iostream header file and template code for c++. A description of the snippet is also added. “\t” and “\n” are added for proper formatting of code.

This is the snippet code result.

The tab is on the 6th line with four spaces.

Snippet Outcome





#include <iostream>
using namespace std;
 
int main()
{
     
    return 0;
}

Video Demo:

Here all the above-mentioned steps are performed creating a Snippet. This will give you a clearer understanding. 

That’s all. In this way, you can create a user snippet for different languages in Visual Studio Code. Each snippet is associated with a particular name, When we type that name and hit the enter key, Snippet code is executed.

Article Tags :