I have a global variable and a local variable with the same names. Can I copy the local variable to the global variable (assign) without first assigning the value of the global variable to some temporary variable (using extern) and then assigning the temporary variable to the global variable? I need to do something like this:
#include<stdio.h>
int myVariable = 50;
void myFunction()
{
int myVariable;
myVariable /*global*/ = myVariable /*local*/;
}
Is there some way in C to do it (without using temporary variables (or pointers in case of arrays))? I found it's possible in C++, Java or C# using keywords like this, super, base, etc. but couldn't find a solution in C.
I have already referred to How can I access a shadowed global variable in C?
In C99 there is no way to specify the specific scope of the variable/constant you want to use. It will automatically refer to the inner-most scope when referring to a variable/constant.
From the C99 standard 6.2.1.4:
... If an identifier designates two different entities in the same name space, the scopes might overlap. If so, the scope of one entity (the inner scope) will be a strict subset of the scope of the other entity (the outer scope). Within the inner scope, the identifier designates the entity declared in the inner scope; the entity declared in the outer scope is hidden (and not visible) within the inner scope ...
So how would I get around this?
Simple, change the name of the inner-most scope variable :)
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