On 6/27/19 3:57 AM, Juha Nieminen wrote:
> Ralf Goertz <m...@myprovider.invalid> wrote:
...
>> I thought a little about that. While I can see your point, I remember
>> having heard (I am no professional programer, so I never properly learnt
>> C++) that every variable should be declared where it is first used.
That's not always possible, if the scope for the variable needs to be
larger than the scope in which the first use occurs.
The key requirement is that it be declared no later than first use, and
preferably as late as possible, consistent with the way it will be used.
>> Which somewhat conflicts with your statement:
>
> That's a principle relating to syntax, not relating to where objects
> should be created. In old C variables needed to be declared at the
> beginning of the function, even if they were only needed later in
> the code. ...
That may have been true in the very earliest days of C, but it hasn't
been true since at least K&R C, which allowed you to declare objects at
the start of any compound statement, not just at the start of the
outermost compound statement of a function:
int func(in)
int in;
{
if(in)
{
int total;
...
C++ added the ability to intermingle declarations and statements, which
was later adopted by C99 as well. However, the freedom to place
declarations in positions other than the start of the function dates
back at least to K&R C.
...
> Obviously the advise is not saying that if you have some buffer of fixed
> size for calculations, and this buffer is used inside the innermost loop
> of a heavy algorithm, you should create the buffer again and again inside
> that inner loop.
Actually, I would not hesitate to define a buffer as a C style array
inside a loop, if there's no need for the contents of that buffer to
carry over from one pass of the loop to another. I would normally expect
the compiler to simply reuse the same piece of memory during each pass
through the loop, at no extra cost.
This is particularly true if there's a need to zero initialize the
buffer between passes, which can be achieved by simply providing a {0}
initializer for the buffer, rather than having to call memset().
In C++, I would hesitate to define a standard container in that
location, because I couldn't rely on the compiler to figure out how to
optimize away the constructor and destructor calls that nominally must
occur at the start and end of each pass through the loop.