Movatterモバイル変換


[0]ホーム

URL:


Skip to main content

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Download Microsoft EdgeMore info about Internet Explorer and Microsoft Edge
Table of contentsExit focus mode

Edit and refactor C++ code in Visual Studio

  • 2022-09-22
Feedback

In this article

Visual Studio provides several tools to help you write, edit, and refactor your code.

IntelliSense

IntelliSense is a powerful code completion tool that suggests symbols and code snippets for you as you type. C++ IntelliSense in Visual Studio runs in real time, analyzing your codebase as you update it and providing recommendations. As you type more characters, the list of recommended results narrows down.

Screenshot of the C plus plus member list drop down showing the methods available for string such as append, assign, and so on.

Some symbols are omitted automatically to help narrow down the results. For example, when accessing a class object's members from outside the class, you won't be able to see private members by default, or protected members (if you aren't in the context of a child class). You can adjust the filtering by using the buttons at the bottom.

After you choose the symbol from the drop-down list, you can autocomplete it withTab,Enter, or one of the other commit characters (by default:{ } [ ] ( ) . , : ; + - * / % & | ^ ! = ? @ # \). To add or remove characters from this list,search for "IntelliSense" inQuick Launch (Ctrl + Q) and choose theText Editor > C/C++ > Advanced option. TheMember List Commit Characters option enables you to customize the list with the changes you want.

TheMember List Filter Mode option controls what kinds of IntelliSense autocomplete suggestions you see. By default, it's set toFuzzy. In a fuzzy search, if you have a symbol calledMyAwesomeClass, you can type "MAC" and find the class in your autocomplete suggestions. The fuzzy algorithm sets a minimum threshold that symbols must meet to show up in the list.Smart filtering displays all symbols containing substrings that match what you typed.Prefix filtering searches for strings that begin with what you typed.

For more information about C++ IntelliSense, seeVisual C++ IntelliSense andConfigure a C++ project for IntelliSense.

IntelliCode

IntelliCode is AI-assisted IntelliSense. It puts the most likely candidate at the top of your completion list. IntelliCode recommendations are based on thousands of open source projects on GitHub each with over 100 stars. When combined with the context of your code, the completion list is tailored to promote common practices.

When writing C++, IntelliCode will assist when using popular libraries such as the C++ Standard Library. The context of your code is used to provide the most useful recommendations first. In the following example, thesize member function is commonly used with thesort function, so it's surfaced to the top of the results list.

Screenshot of C plus plus IntelliCode dropdown which shows the members of the vector class sorted by which are most commonly used in your code.

In Visual Studio 2022 and Visual Studio 2019, IntelliCode is available as an optional component in theC++ Desktop Development workload. To make sure that IntelliCode is active for C++, go toTools >Options >IntelliCode >General and setC++ base model toEnabled.

In Visual Studio 2017, IntelliCode is available as an extension in the Visual Studio Marketplace.

Predictive IntelliSense (Experimental)

Predictive IntelliSense is an experimental feature that uses contextual awareness to limit the number of results displayed in the IntelliSense dropdown list. The algorithm applies type matching so that it shows only those results that match the expected type. In the simplest case, if you typeint x = and invoke the IntelliSense dropdown, you will see only integers or functions returning integers. This feature is off by default because it's still in development. It works best with global symbols; member functions aren't yet supported. You can turn it on by typing "Predictive" inQuick Launch or by going toTools >Options >Text Editor >C/C++ >Experimental >Enable Predictive IntelliSense.

To overridePredictive IntelliSense and show the longer list, pressCtrl + J. IfPredictive IntelliSense is on, invokingCtrl + J removes the Predictive filter. PressingCtrl + J again removes the accessibility filter from Member List results where relevant. The ([+]) button under the IntelliSense dropdown list does the same thing asCtrl + J. Hover over the button to see tooltip information about what is being shown.

Screenshot of C plus plus Predictive IntelliSense.

The preceding screenshot shows several buttons under the dropdown list. These enable IntelliSense Filters for different kinds of results:

  • Variables and Constants
  • Functions
  • Types
  • Macros
  • Enums
  • Namespaces

A button is displayed only if it's relevant to your current IntelliSense session. You typically don't see all the buttons at the same time.

Template IntelliSense

The template bar is a UI element that appears when your cursor is on a template definition. It's useful because you can provide sample template arguments for intellisense that will appear when you edit the template body. For example, you could specify that a template argument is of typestd::vector<int>. Then, when you use that argument in the template body, you'll see the members ofstd::vector<int>in intellisense.

Screenshot of the template bar which has the Add All Existing Instantiations option highlighted.

Click the<T> icon to expand/collapse theTemplate Bar. Click the pencil icon or double-click theTemplate Bar to open theEdit window where you specify argument types for the parameters.

Screenshot of the editing experience inside the template bar where you enter a type for each template parameter.

The Template Bar can auto-populate parameter types based on instantiations of the template in your code. Click onAdd All Existing Instantiations to see a list of all concrete arguments that have been used to instantiate the template throughout your code base.

Screenshot of the Template IntelliSense Results listing the different types used to instantiate template parameter C such as C = AmbientLight, C = Candle, and others.

A window at the bottom of the editor shows where each instantiation was found, and what its arguments were. You can select an instantiation to go to the location in your code where that instantiation was found.

Screenshot of the list of instantiations of the template in your code. The instantion, file, location, and arguments are listed.

Template Bar information is user-specific. It's stored in the.vs folder and isn't committed to source control.

Error squiggles and quick fixes

If the editor detects problems with your code, it will add colored squiggles under the problem. Red squiggles indicate code that won't compile. Green squiggles indicate other kinds of problems that might still be potentially serious. You can open theError List window to get more information about the problems.

For some kinds of errors, and common coding patterns, the editor will offer aQuick Fix in the form of a light bulb that appears when you hover over the squiggle. Click the down arrow to see the suggestions.

In the following example, avector was declared but no definition was found, so the editor offers to include the necessary header file:

Screenshot of an error and the proposed quick fix to # include vector.

The editor also offers Quick Fixes for some refactoring opportunities. For example, if you declare a class in a header file, Visual Studio will offer to create a definition for it in a separate .cpp file.

Screenshot showing the quick fix with the Create definition of Channel Route Iterator in channels dot C P P option highlighted.

Change tracking

Whenever you make a change to a file, a yellow bar appears on the left to indicate that unsaved changes were made. When you save the file, the bar turns green. The green and yellow bars are preserved as long as the document is open in the editor. They represent the changes that were made since you last opened the document.

Screenshot of C plus plus change tracking. A yellow bar down the left appears to indicate changes.

Move code

You can move lines of code up and down by selecting them, holding down Alt, and pressing theUp/Down arrow keys.

Insert snippets

A snippet is a predefined piece of source code. Right-click on a single point or on selected text and select Snippet to either insert a snippet or surround the selected text with the snippet. The following illustration shows the three steps to surround a selected statement with a for loop. The yellow highlights in the final image are editable fields that you access with the tab key. For more information, seeCode Snippets.

Screenshot of the Insert Snippet Drop down control.

A function is selected. In the dropdown that appears after a right-click on the function name, Surround With... is highlighted in yellow. In the Surround With: dropdown, the snippet for a `for` loop is selected. This results in putting a for loop around the function. The loop variable and limit are shown in yellow to indicate that they are editable fields.

Add Class

Add a new class from theProject menu, or from the context menu inSolution Explorer:

Screenshot of the Add New Class dialog. It has fields for the class name, accessibility, files to put the declaration and implementation, and so on.

You can also use Class Wizard to modify or examine an existing class.

Screenshot of the Class Wizard which has options for adding methods, member variables, and much more.

For more information, seeAdding Functionality with Code Wizards (C++).

Refactoring

Refactorings are available under the Quick Action context menu, or by clicking on alight bulb in the editor. Some are also found in theEdit > Refactor menu. These features include:

Code style enforcement with ClangFormat and EditorConfig

Visual Studio 2017 and later comes with built-in support forClangFormat, a popular code-formatting utility for C++ based on Clang/LLVM. Type "ClangFormat" intoQuick Launch to set it to use one of these common formats:

  • LLVM
  • Google
  • Chromium
  • Mozilla
  • WebKit
  • Visual Studio

You can also provide your own.clang-format or_clang-format file to apply custom rules to all code files at the same level or below.

The files are easily shareable via source control, so you can enforce coding conventions across your whole development team.

Screenshot showing a .clang-format file which has many options such as the column limit, indent width, tab width, and so on.

Visual Studio 2017 and later also supportsEditorConfig, which works in a similar way. ClangFormat, however, has more style options than EditorConfig, including rules that are specific to C++. WithEditorConfig, you create.editorconfig files and place them in different folders of your codebase to specify code styles for those folders and their subfolders. An.editorconfig file supersedes any other.editorconfig files in parent folders and overwrites any formatting settings configured viaTools >Options. You can set rules for tabs vs. spaces, indent size, and more. For more information, seeCreate portable, custom editor settings with EditorConfig.

Other formatting options

TheQuick Launch search box provides the fastest way to find a setting or tool. It's located on the main menu. Just start typing and the auto-completion list will filter the results.

Screenshot of the Quick Launch search box. It shows searching C plus plus advanced which results in options for the text editor.

To set formatting options such as indents, brace completion, and colorization, type "C++ Formatting" into theQuick Launch window.

Screenshot showing C++ formatting options such as whether to automatically indent when you type a tab.

Other formatting options are found underEdit >Advanced in the main menu.

Screenshot showing advanced editing options such a viewing white space, word wrap, commenting a selection, increasing line indent, and more.

Options for enabling and configuring C++-specific editing features are located underTools >Options >Text Editor >C/C++. After choosing which option you want to set, you can get more help by pressingF1 when the dialog is in focus. For general code formatting options, typeEditor C++ intoQuick Launch.

Screenshot showing the Visual Studio menu item Tools selected, and the Options menu item highlighted.

Experimental features, which may or may not be included in a future version of Visual Studio, are found in theText Editor C++ Experimental dialog. In Visual Studio 2017 and later you can enablePredictive IntelliSense in this dialog.

See Also

Read and understand C++ code
Navigate your C++ code base in Visual Studio
Collaborate with Live Share for C++


Feedback

Was this page helpful?

YesNo

In this article

Was this page helpful?

YesNo