I am reading a book on the C language ('Mastering C'), and found the topic on scope resolution operator (::
) on page 203, on Google Books here.
But when I run the following code sample (copied from the book), the C compiler gives me an error. I searched on the internet but I am unable to find any reference to a scope resolution operator in C.
#include <stdio.h>
int a = 50;
int main(void)
{
int a =10;
printf("%d",a);
printf("%d\n", ::a);
return 0;
}
So if I want to access a global variable then how could I do that from within the main()
function ?
No. C does not have a scope resolution operator. C++ has one (
::
). Perhaps you are (or your book is) confusing C with C++.You asked how you could access the global variable
a
from within a function (heremain
) which has its own local variablea
. You can't do this in C. It is lexically out of scope. Of course you could take the address of the variable somewhere else and pass that in as a pointer, but that's a different thing entirely. Just rename the variable, i.e. 'don't do that'::
operator is available in C++ not C. If you wanted to access the global variable, useOr you could use a pointer which holds the address of the global variable
a
and then dereference the pointer if you want to print the value of the global variablea
.No (the
::
operator is C++ specific). In C, if you use the same identifier in different overlapping scopes (say, file scopea
and block scopea
), the block scope identifier shadows the file scope identifier and there is no way to refer to the shadowed identifier.It is generally best programming practice to avoid shadowed variables. Many lint type programs can warn about this situation.
You may use pointers to access and edit global variables in C.
In plain C, there is no scope resolution. You have to name your variables differently.
That means that all variables
a
below are different ones:No, namespaces are a feature of C++.
It is, however, possible to refer to global
a
in your example. You can achieve this by using theextern
keyword:That's a bit tricky, though. It's bad style. Don't do that.