CS 228 lecture -*- Outline -*- * declarations (A.10-11) ** definitions vs. decarations (A.11, page A-29) ------------------------ DEFINITIONS VS. DECLARATIONS declaration: tells the reader about the properties of a name extern int square(int i); extern int count; definition: is a declaration that also gives a value for the name, or allocates storage int square(int i) { return i * i; } int count; ------------------ in general, extern can be used with declarations. see the refenrece materials for more details ** definitions (A.10) --------------------------- DEFINITIONS Constants: const char BLANK = ' '; const double PI = 3.141593; Variables: char b; char c = 'c'; double root; ----------------------------- note that variables don't have to be initialized, but constants do ----------------------------- Types: enum FlagColor {red, white, blue}; typedef int miles; typedef char *string; Functions: void prompt(string promptstring) { cout << promptstring << flush; } ----------------------------- ** scope rules (A.11) summary: basically like Scheme, or Pascal *** scope units ---------------------------- SCOPES IN C++ local to a block: if (discriminant > 0) { double sqrt_d = sqrt(discriminant); ... } // sqrt_d declaration not visible file scope: extern void prompt(string promptstring); ... int main() { ... prompt("a? "); ... } Scope of a declaration extends from point of declaration to end of block or file (as appropriate). ---------------------------- note that a function body is a block also class scope, but we haven't seen classes yet... *** lifetime of variables ------------------------ VARIABLE LIFETIME def: the lifetime of a variable is the time when it's active. automatic storage class (default): int j; int i = f(whatever); lifetime is from time of definition to time when block exited initialized each time, initializer arbitrary expression. static storage class: static double foo; static int count = 0; lifetime is from start of program execution to the end of the program. initialied only once, initializer constant expression -------------------------