Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy local variable to global variable if both have the same names in C without using a third variable?

Tags:

c

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?

like image 991
Sachin Joseph Avatar asked Aug 14 '13 18:08

Sachin Joseph


1 Answers

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 :)

like image 199
Jacob Pollack Avatar answered Sep 21 '22 16:09

Jacob Pollack