Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counterpart of PHP's isset() in C/C++

PHP has a very nice function, isset($variableName). It checks if $variableName is already defined in the program or not.

Can we build similar feature for C/C++ (some kind of symbol table lookup)?

like image 228
VarunGupta Avatar asked Oct 23 '08 17:10

VarunGupta


2 Answers

I'm a C++ guy, but I remember in PHP isset is used to check if a variable contains a value when passed in through a get/post request (I'm sure there are other uses, but that's a common one I believe).

You don't really have dynamic typing in C++. So you can't suddenly use a variable name that you haven't previously explicitly defined. There really is no such thing as an "unset" variable in C++.

Even if you say "int var;" and do not initialize it, the variable has a value, usually garbage, but it's still "set" in the PHP sense.

The closes I suppose would be the preprocessor's #ifdef and #ifndef which only checks to see if you've defined a variable using #define. But in my experience this is mostly used for omitting or adding code based on flags. For example:

// code code code
#ifdef DEBUG
// debug only code that will not be included in final product.
#endif
// more code more code

You can define DEBUG using #define to determine whether to include "DEBUG" code now.

Perhaps telling a bit more about what you're trying to do with the C++ equivalent of isset will give you a better idea of how to go about doing it "The C++ Way".

like image 57
Jeffrey Martinez Avatar answered Sep 22 '22 03:09

Jeffrey Martinez


There is no direct means of doing this in the language. However, it is possible to do this sort of thing by using a map such as the following:

typedef std::map<std::string, int> variables_type;
variables_type variables;

variables["var"] = 1;
if(variables.find("jon") == variables.end())
   std::cout << "variable, \"jon\" not set\n";

In order to make this a variable like those used in PHP or javascript, the implementation would need to use some sort of variant type.

like image 35
Jon Trauntvein Avatar answered Sep 24 '22 03:09

Jon Trauntvein