#include #include using namespace std; extern char **environ; void PrintValue(string value); int main() { string name{"SILLY"}; cout << endl; // the c++ compiler has trouble with casting a const char * to a char * // any of the three of these are fine. // See the notes. #if defined(CASE1) string sillyVar{"SILLY=Now I am"}; cout << "\tusing string sillyvar " << endl; #elif defined(CASE2) char* sillyVar = strdup("SILLY=Now I Am"); cout << "\tUsing char* sillyVar" << endl; #elif defined(CASE3) const char* sillyVar{"SILLY=Now I Am"}; cout << "\tUsing const char* sillyVar" << endl; #else char sillyVar[] = "SILLY=Now I Am"; cout << "\tUsing char sillyVar[] " << endl; #endif cout << endl; PrintValue("LOGNAME"); PrintValue(name); cout << "The environ pointer is " << environ << endl; #ifdef CASE1 if (putenv(const_cast(sillyVar.c_str())) == -1) { #else #ifdef CASE3 if (putenv(const_cast(sillyVar)) == -1) { #else if (putenv(sillyVar) == -1) { #endif #endif cerr << "Unable to change the SILLY environment variable" << endl; } else { PrintValue(name); } cout << "The environ pointer is " << environ << endl; #ifdef CASE2 free(sillyVar); #endif return 0; } void PrintValue(string name) { char * tmp; cout << endl; cout << "Searching for " << name << endl; cout << "\t"; tmp = getenv(name.c_str()); if (tmp != nullptr) { cout << name << " is " << tmp << endl; } else { cout << name << " is not in the environment. "<< endl; } cout << endl; return; }