Important Notice: Our web hosting provider recently started charging us for additional visits, which was unexpected. In response, we're seeking donations. Depending on the situation, we may explore different monetization options for our Community and Expert Contributors. It's crucial to provide more returns for their expertise and offer more Expert Validated Answers or AI Validated Answers. Learn more about our hosting issue here.

What is the convention (for declaring variables) in C++? Is it moving toward limited scope declarations or is it keeping to the function level scope of C?

0
Posted

What is the convention (for declaring variables) in C++? Is it moving toward limited scope declarations or is it keeping to the function level scope of C?

0

The answer is not really language specific. As a general rule, it is good to limit the scope of variables; however it is also good to write readable code. These goals are not necessarily served by the same hard rules. C++ and Perl allow the declaration of variables just about anywhere in the block, whereas other languages require declarations to be made at the beginning of the block. Thus C++ and Perl give you more flexibility as a code engineer. Often I find that readability and correctness are served by dividing the variables into two categories: “meaningful” and “meaningless” to the computation. By this I mean meaningful or meaningless to an outside observer who knows what computation is being done, but not necessarily the details of how it is carried out. This is a judgement call, of course. An example of “meaningful” would be “sum” and “size” in calculating the mean of an array of integers. An example of “meaningless” would be the index variable in a loop that accumulates the sum.

Related Questions

What is your question?

*Sadly, we had to bring back ads too. Hopefully more targeted.

Experts123