Should I narrow down the scope of the variable as much as possible even if I put it in for?

Asked 2 years ago, Updated 2 years ago, 39 views

This is a rudimentary question. Suppose you have the following code.

 for (inti=0;i<100;++i)
{
    inta=i;
    std::cout<<a<<std::endl;
}

Here, a is only used in for, but I don't think it's efficient to put it in for and declare it over and over again just because it's better to make the scope as small as possible. That is,

 inta;
for (inti=0;i<100;++i)
{
     a = i;
    std::cout<<a<<std::endl;
}

Is there any inconvenience with programs like this other than increasing the scope?

java c++ c

2022-09-30 18:18

3 Answers

The C++ language has a constructor destructor.

inta=i;

is initialized with i but

 inta;
a = i;

The initializes empty and then copies and substitutes i.The latter also runs immediately after the end of the for loop, but the former stays alive until it leaves the scope.
Simple integers make no difference, but you should always be aware of the appropriate variable scope for versatility.

In this connection, the C++ language has been enhanced to allow efficient variable declaration in if and switch as well as for.Separate conditional expressions and initializations between if and switch statements


2022-09-30 18:18

However, I think it's inefficient to put it in for and declare it over and over again just because it's better to make the scope as small as possible

Actively reduce the scope as memory efficiency remains the same and execution speed increases readability.


2022-09-30 18:18

After reading the questionnaire, I understood that there are concerns about the cost of declaring variables.
I've had the same question before, and I've looked into Java (Java 5) and C (GCC 4.4.3).

In conclusion, whether you declare outside the loop or inside, the efficiency is exactly the same .
After compilation, the byte code/assembly did not have information that the variable was declared.In other words, local variable declaration costs zero.


2022-09-30 18:18

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.