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
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
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.
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.
© 2024 OneMinuteCode. All rights reserved.