About using multiple blocks with scope in C ++ - functions

I am starting to get more and more involved in writing long algorithmic functions in C ++ using the following blocks:

void my_algorithm(const MyStruct1 &iparam1, MyStruct2 &oparam2) { // First block MyStruct3 intermediate_var3; { double temporary_var; // Functional step 1.1 // Functional step 1.2 intermediate_var3 = ... } // Second block MyStruct4 intermediate_var4; { double temporary_var; // Functional step 2.1 // Functional step 2.2 intermediate_var4 = ... } // Final block { int temporary_var; oparam2 = ... } } 

I'm starting to think that this is a good way to clarify the structure of functions and limit the scope of temporary variables (such as counters i , j , k , etc.). I have seen that such area blocks make sense in C functions to include new declarations (see Why enclose C code blocks in curly braces? ).

In a C ++ context, is this a good or bad practice?

0
source share
1 answer

This is a clear sign that you should separate these individual blocks into separate functions.

 MyStruct3 DoSth3(params) { double temporary_var; // Functional step 1.1 // Functional step 1.2 return ... } MyStruct4 DoSth4(params) { double temporary_var; // Functional step 2.1 // Functional step 2.2 intermediate_var4 = ... } void my_algorithm(const MyStruct1 &iparam1, MyStruct2 &oparam2) { // First block MyStruct3 intermediate_var3 = DoSth3(params); // Second block MyStruct4 intermediate_var4 = DoSth4(params); int temporary_var; oparam2 = ... } 

You might be worried that DoSth3 and DoSth4 are publicly available, as they should be private in the context of my_algorithm . In this case, you can solve it as follows:

 class my_algorithm { private: static MyStruct3 DoSth3(params); static MyStruct4 DoSth4(params); public: static void Perform(const MyStruct1 &iparam1, MyStruct2 &oparam2); }; 
+1
source

Source: https://habr.com/ru/post/988076/


All Articles