Evil_Transistor
Evil_Transistor

Reputation: 378

What is #pragma region in c++ and VScode?

I found out that we can hide code in VScode using #pragma region and #pragma endregion. I have two questions:

  1. How does #pragma region work?
  2. Will it affect compilation if I tried to compile the code on any other machine?

Upvotes: 18

Views: 27098

Answers (2)

stackoverflowuser2010
stackoverflowuser2010

Reputation: 40899

First, #pragma is a C preprocessor directive. You're undoubtedly familiar with the #include and #define directives. Directives are used by the C preprocessor to perform certain actions before the code reaches the compiler.

The #pragma directive in particular is meant to pass implementation-specific information to whatever compiler you're using.

Here's what GNU has to say:

The #pragma directive is the method specified by the C standard for providing additional information to the compiler, beyond what is conveyed in the language itself.

Here's what Microsoft has to say:

Pragma directives specify machine-specific or operating system-specific compiler features.

Second, for Microsoft Visual Studio and Visual Studio Code, the #pragma region directive defines a region of code that the compiler's UI can use for code-folding (that is, hiding and showing blocks of code for readability). If a compiler cannot understand the #pragma region directive, then the directive is ignored.

Here's an example below:

  1. Here's a chunk of C++ code in Visual Studio Code v1.60.0 (2021) on Mac. It would be great if I could hide and unhide the private: chunk of code. Note that when I mouse-over the UI, there is a down arrow chevron (⌄) to indicate foldable code for the comment block but not for the private: block.

enter image description here

  1. Putting in a starting #pragma region foo and ending #pragma endregion will identify a block of code for code-folding. Notice that after the two #pragma directives are added, the code-foldable chevron symbol appears in the UI.

enter image description here

  1. When you click on the chevron, the demarcated block will fold (hide). Clicking on the chevron again will unfold the block.

enter image description here

Upvotes: 16

AngryParticle
AngryParticle

Reputation: 1539

The #pragma region is specific to Visual Studio only.

Using #pragma region you can specify a block of code where you can expand it and collapse it.

It has no affect on compilation.

Here is an example:

// pragma_directives_region.cpp
#pragma region Region_1
void Test() {}
void Test2() {}
void Test3() {}
#pragma endregion Region_1

int main() {}

You can read more about it here.

Like others have mentioned your compiler is allowed to silently ignore a pragma, Some will even give a warning depending on the specific compiler you are using. You need to read about your compiler's docs on pragma.

gcc -Wall also check for unknown pragmas.

Upvotes: 31

Related Questions