Personal tools
You are here: Home development ScopeInC
Views

Edit history

Edit: -1 of 1
Time: 2008-07-31 02:55:30
Note: /pd/pd/dev/ScopeInC/edit

changed:
-
----
This is a scratchpad to work out examples of how scope works in C.

== Levels ==
 * global
 * file  (i.e. static functions/variables)
 * function
 * block (i.e. within brackets)

== Preprocessor definitions ==
 * `#define` and `#include` is per-file
 * `#include` imports other `#define`s and `#include`s into the file


== Variables ==

With variables, symbols declared at or above the current level are visible:

{{{
int myGlobalInt;           /* global */
static myGlobalPerFileInt; /* file */
void myFunction(void() {   
    int myFunctionInt;     /* function */
    {
        int myInt;         /* block */
    }
}
}}}

{{{
#include <stdio.h>
int i = 1;                         /* i defined at file scope */

int main(int argc, char * argv[]) {
    printf("%d\n", i);              /* Prints 1 */
    {
        int i = 2, j = 3;            /* i and j defined at block scope */
        printf("%d\n%d\n", i, j);    /* Prints 2, 3 */
        {
            int i = 0;  /* i is redefined in a nested block */
            /* previous definitions of i are hidden */
            printf("%d\n%d\n", i, j); /* Prints 0, 3 */
        }
        printf("%d\n", i);           /* Prints 2 */
    }
    printf("%d\n", i);              /* Prints 1 */
    return 0;
}
}}}

== References ==
 * [http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=/com.ibm.xlcpp8a.doc/language/ref/zexscope_c.htm Examples of scope in C]
 * [http://nob.cs.ucdavis.edu/bishop/papers/1986-cjourv2n1/ Scope in C]
 * [http://www.newtonlabs.com/ic/ic_9.html Interactive C User's Guide - Preprocessor]



Powered by IEM Powered by Plone Section 508 WCAG Valid XHTML Valid CSS Usable in any browser