Create Tests
#include#include using namespace std; void fa(); void fb(); void fc(); void func ( const int & i ); void func ( const string & fs ); void func2 ( const string * fs ); void func3 ( const string * fs ); const char * prompt(); int jump ( const char * ); void (*funcs[])() = { fa, fb, fc, nullptr }; int main( int argc, char ** argv ) { int x = 24; string s = "Hello"; puts ("this is main()"); func(x); x = 73; printf ("x is %d\n", x); func(&s); printf ("string is %s\n", s.c_str()); func2(&s); printf ("string2 is %s\n", s.c_str()); printf ("returned string is %s\n", func3().c_str()); // function pointer *fp void (*fp)() = func4; void (*fp)(&s) = &func4; // same as above fp(); // or (*fp)(); while ( jump (prompt()) ); puts ("\nDone\n"); fflush(stdout); return 0; } void func( const int & i ) { // would result in error if you try to change i in function printf ("value is %d\n", i); } void func( const string & fs ) { printf ("String is %s\n", fs.c_str()); } void func2 (const string * fs ) { printf ("String2 is %s\n", fs->c_str()); } // declare to be const so you can't change the string const string & func3 (const string * fs ) { // declare to be static storage so the stack for function won't // overflow and create security problem // auto is deprecated, because it's default and stored in stack // stack is created fresh for each function // // also if you have to return a reference, declare it to be static // so it can be stored in static storage space // auto storage on stack is small. Use reference if you have // to return big object and return the reference in static storage static string s = "This is static"; return s; } void func4() { printf ("String2 is %s\n", fs->c_str()); puts ("a string"); } void func4(const string * fs) { printf ("String2 is %s\n", fs->c_str()); puts ("a string"); } const char * prompt() { puts ("Choose an option:"); puts ("1. do fa()"); puts ("2. do fb()"); puts ("Q. quit"); puts ("Choose an option:"); printf(">> "); fflush(stdout); // flush after prompt const int buffsz = 16; // constant for buffer size static char response [buffsz]; // static storage for response buffer fgets(response, buffsz, stdin);// get response from console return response; } int jump ( const char * rs ) { char code = rs[0]; if (code == 'q' || code == 'Q') return 0; // count the length of the funcs array int func_length = 0; while ( funcs[func_length] != Null ) func_length++; int i = (int) code - '0'; // convert ASCII numeral to int i--; // list is zero-based if ( i < 0 || i >= func_length ) { puts ("invalid choice"); return 1; } else { funcs[i](); return 1; } }
No comments:
Post a Comment