Reputation: 67057
I have that functionality inside a function that is encapsulated within an #ifdef
block that has an if()
statement attached to it:
int myfunction(void) {
int condition = 0;
#ifdef USE_WHATEVER
int othervar = 0;
#endif /* USE_WHATEVER */
/* some code */
#ifdef USE_WHATEVER
if( condition ) {
othervar++;
/* do other things with othervar */
}
#endif /* USE_WHATEVER */
The variable othervar
is only used inside the #ifdef
block. Since the whole #ifdef
block is an if
statement, I could pull the declaration of othervar
inside the if
block:
int myfunction(void) {
int condition = 0;
/* some code */
#ifdef USE_WHATEVER
if( condition ) {
int othervar = 0;
othervar++;
/* do other things with othervar */
}
#endif /* USE_WHATEVER */
This seems much cleaner to me than the first example. However, are there any drawbacks (performance, ...) of doing such?
Upvotes: 1
Views: 234
Reputation: 33273
In c89, variables can only be declared at the beginning of a block. Some ppl/coding standards would put all variable declarations at the top of the function, like you are seeing here. However, variables may be declared at the beginning of any block.
You need to consider the scope of othervar
. If it is used only inside the if
block then it is safe to move the declaration to the beginning of the if
block.
There should not be any performance drawback. The compiler is not unlikely to generate the exact same code for the two cases.
Upvotes: 1
Reputation: 199
No, there is no drawback as such unless you want to use the variable within the block scope.The only problem is that this kind of definition i.e. definition of variable in between the code might not be accepted in some standard.
Upvotes: 0