In the C programming language, it is my understanding that variables can only be defined at the beginning of a code block, and the variable will have the scope of the block it was declared in. With that in mind, I was wondering whether it is considered bad practice to artificially create a new scope as in this example:
void foo()
{
... Do some stuff ...
if(TRUE)
{
char a;
int b;
... Do some more stuff ...
}
... Do even more stuff ...
}
Assuming TRUE is set to 1 in a macro definition, would this code be considered 'good code' or does it make seasoned programmers cringe at the very thought of it?
Thanks for your input!
EDIT: In response to some of the answers, the code I am working with needs to work with some pretty ancient legacy systems. While it would be nice to operate on an assumption of C99, we really can't guarantee that they will have it.
A true boolean data type could be used for storing logical values, and would only have two legal values - "true", and "false". C does not have boolean data types, and normally uses integers for boolean testing. Zero is used to represent false, and One is used to represent true.
In standard C, any non-zero (positive/negative) value is TRUE. So, (-1) evaluated as TRUE and, !(- 1) of-course evaluated as FALSE.
The if statement allows you to control if a program enters a section of code or not based on whether a given condition is true or false.
You don't even need an if statement. You can create blocks with {}
That should probably be a separate function however.
Example here:
#include <stdio.h>
int
main(int argc, char **argv) {
int i = 0;
{
int i = 10;
printf("%d\n", i);
}
printf("%d\n", i);
}
As far as I know you can create a scope without if.
Use just the braces like this:
{
int x;
}
And I recommend against
if (TRUE)
since it hinders readibility.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With