Introduction
Many "C-like" programming languages use compound statements (code blocks specified with "{" and "}") to define a variables scope.
Here is a simple example.
for (int i = 0; i < 100; ++i) {
int value = function(i); // Here 'value' is local to this block
printf("function(%d) == %d\n", i, value);
}
This is good because it limits the scope of the value
to where it is used. It is hard for programmers to use value
in ways that they are not meant to because they can only access it from within its scope.
I am almost all of you are aware of this and agree that it is good practice to declare variables in the block they are used to limit their scope.
But even though it is an established convention to declare variables in their smallest possible scope it is not very common to use an naked compound statement (that is an compound statement that is not connected to an if
, for
, while
statement).
Swapping the values of two variables
Programmers often write the code like this:
int x = ???
int y = ???
// Swap `x` and `y`
int tmp = x;
x = y;
y = tmp;
Would it not be better to write the code like this:
int x = ???
int y = ???
// Swap `x` and `y`
{
int tmp = x;
x = y;
y = tmp;
}
It looks quite ugly but I think that this is a good way to enforce variable locality and make the code safer to use.
This does not only apply to temporaries
I often see similar patterns where a variable is used once in a function
Object function(ParameterType arg) {
Object obj = new Object(obj);
File file = File.open("output.txt", "w+");
file.write(obj.toString());
// `obj` is used more here but `file` is never used again.
...
}
Why don't we write it like this?
RET_TYPE function(PARAM_TYPE arg) {
Object obj = new Object(obj);
{
File file = File.open("output.txt", "w+");
file.write(obj.toString());
}
// `obj` is used more here but `file` is never used again.
...
}
Summary of question
It is hard to come up with good examples. I am sure that there are betters ways to write the code in my examples but that is not what this question is about.
My question is why we do not use "naked" compound statements more to limit the scope of variables.
What do you think about using a compound statement like this
{
int tmp = x;
x = y;
y = z;
}
to limit the scope of tmp
?
Is it good practice? Is it bad practice? Explain your thoughts.
x
andy
would be declared outside, then passed into a function calledswap
, and inswap
would be a variable calledtemp
.std::swap()
.