Variable Declaration and Scope

<< Click to Display Table of Contents >>

Navigation:  Concordance Programming Language Reference >

Variable Declaration and Scope

Variables are declared by stating their type followed by their name.  Several variables of the same type can be declared at once by stating their names separated by commas.

int i, count, WayDownTheRoad;

char string[20], ch;

Variable declarations, like all CPL statements, are terminated by a semi-colon. Variable names can be any CPL identifier.

By default, all variables start with the initial value of zero. Optionally, they can be declared and initialized in the same statement.

int x, y = 2, z, maximum = 25;

Global variable declarations must take place outside any function declaration. Globally declared variables are visible and accessible to all functions. Local variables, those declared between a function’s opening { and closing } braces, are visible and accessible only to the declaring function. All variables must be declared before they are used.

Local variable declarations must take place immediately following a function’s opening { brace and prior to the first executable statement. Local variables come into existence when the function is active and disappear when the function returns. Local variables can only be accessed by the function that declared them and only while it is executing. The one exception to this is when a function passes a locally declared array to another function. In this instance the receiving function can modify the original data. Arrays are passed by name alone, without subscription. In all other cases a called function gets a copy of the parameter, not the original variable.

Example:

something()

{

int a[1], b, c[1];

a[0] = 1;

b = 2;

c[0] = 3;

nothing(a,b,c[0]);

/* a[0] now contains 5 */

/* b still contains 2 */

/* c[0] still contains 3 */

}

nothing(int x[], y, z)

{

x[0] = 5;

y = 10;

z = 15;

}

A variable declared within a function with the same name as a global variable will cause the global variable to disappear from the function’s point of view. References to the variable within the function only affects the local variable.

Likewise, a function within a CPL program with the same name as a Concordance function replaces the Concordance function.