CS/CE 218 Lecture -*- Outline -*- connection: the separate compilation mechanism of C has a pleasant side effect; it allows programs to keep design decisions local to a given file. This improves your ability to maintain a program, since changing such decisions only involves changing a single file. * Information Hiding in C idea is to localize information in a program (C doesn't support a complete solution to this problem) another benefit is to reduce the size of the global namespace ** export/import mechanism (files are modules) (section 4.6) Q: How can you hide declarations in a file? Q: How can you allow other files to access a function declared in a file? objects (names of variables or functions) are: exported by giving them the attribute extern (i.e., not declaring them static) default for functions and defs outside functions hidden by giving them attribute static objects are imported by declaring them to be extern -------------- int exported; static int hidden = 3; static int hidden_function(int x) { ... } void globally_known(int y) { ... y = hidden_function(y+1); ... } -------------- ** Info hiding: use static to hide information within a file prevents clients of external procedures from accessing data defined in the file. allows procedures in the same file to manipulate data only perfectly safe if clients are never allowed direct access to the data (as in this example) ---------------- /* file string_set.c */ #include #define MAX_TRACKED_INCLUDES 1000 #define MAX_PATHNAME_LENGTH 500 static char already_included [MAX_TRACKED_INCLUDES] [MAX_PATHNAME_LENGTH]; static int num_tracked = 0; /* rep invariant: no duplicates in already_included */ void string_set_insert(char []) /* effect: put a copy of s in the set */ { /* ... */ } int string_set_has(char []) /* effect: is s in the set? */ { /* ... */ } ---------------- declaring already_included and num_tracked as static hides these, main program can't access them string_set_insert and string_set_has are extern since they aren't declared static. Q: Can num_tracked be used in another file? no Q: Can string_set_has be used in another file? yes ** Data abstraction as a design principle Data abstraction = hiding information about data structures what info? exact declaration algorithms for operating on it. Important because data structures often change. The essence of object-oriented programming.