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)?
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".
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.
Not really. You can't dynamically create variables (though you can dynamically create storage with malloc() et al, or new et al. in C++) in C. I suppose dynamically loaded libraries blur the picture, but even there, the way you establish whether the variable exists is by looking up its name. If the name is not there, then, short of running a compiler to create a dynamically loaded module and then loading it, you are probably stuck. The concept really doesn't apply to C or C++.
As said in other answers, in C++ variables are never undefined. However, variables can be uninitialised, in which case their contents are not specified in the language standard (and implemented by most compilers to be whatever happened to be stored at that memory location).
Normally a compiler offers a flag to detect possibly uninitialised variables, and will generate a warning if this is enabled.
Another usage of isset could be to deal with different code. Remember that C++ is a statically compiled language, and attempting to redefine a symbol will result in a compile time error, removing the need for isset.
Finally, what you might be looking for is a null pointer. For that, just use a simple comparison:
int * x(getFoo());
if (x) {
cout << "Foo has a result." << endl;
} else {
cout << "Foo returns null." << endl;
}
Well there is always Boost.Optional
http://www.boost.org/doc/libs/1_36_0/libs/optional/doc/html/index.html
which should almost do what you want.
Short answer: NO
Standard followup question: What problem are you really trying to solve?
You've got to separate two things here: variable declaration and variable contents.
As said in other answers, unlike PHP, C++ doesn't allow a variable to be used before it's declared.
But apart from that, it can be uninitialized.
I think the PHP isset function tries to find out if a variable has a usable value. In C++, this corresponds best to a pointer being NULL or valid.
The closest thing I can think of is to use pointers rather than real variables. Then you can check fro NULL.
However, it does seem like you're solving wrong problem for the language, or using wrong language to solve your problem.
Related
Can we understand if there is a variable mentioned/created/exists ?
I mean something like that:
//..Some codes
int main(){
int var1;
float var2;
char var3;
cout << isExist("var1") << endl;//Or isExist(/*Something related with var1*/)
cout << isExist("var2") << endl;
cout << isExist("var3") << endl;
cout << isExist("var456") << endl;//There is no variable named with var456
return 0;
}
Output:
true
true
true
false
No. C and C++ do not support reflection.
Not in C/C++. But you could have a look at boost reflect library. http://bytemaster.bitshares.org/boost_reflect/
In C/C++, accessing a variable not defined will generate a compiler error. So, in a sense, that is inherent to how it works. You cannot do that at runtime, at least not as you are trying to do, and should not have need to - because you can't name new variables at runtime in the first place, so you should already know the variables there.
The only way to do this would be indirectly with macros. Macros can't check if a variable itself is defined, but a define could be paired with a variable definition and you could check for the define token.
#define A_VARIABLE 1
int a_variable = 60;
And later:
#ifdef A_VARIABLE
...
#endif
Like most macros, it is probably best to avoid this sort of behavior - however, I have seen it used to deal with platform-dependence of certain variables.
Dynamic memory is a different matter. Since you did not mention it, I will not go into it, but suffice to say it is a more complicated problem which proves the bane of many programmers and the source of many runtime errors.
The 'programming language C' is a human readable form of providing instructions to a computer. All names in the program have only meaning within the program text.
Upon compilation, the names are replaced with a symbolic reference to a storage location or function (execution starting point). Any symbol not found in the current complilation unit (object module) is marked for future resolution.
The object modules are combined (linked) into an executable, where all references to symbols not in an object module are resolved with locations in other object modules; otherwise the creation of the executable fails.
Since now any names have been replaced with references to storage locations and execution starting points, the executable doesn't know anymore about the names used in the program text to refer to its storage locations and functions.
Any ability to do so (the 'reflection' as user #Bill-Lynch calls it) would be 'bolted on' to the language/environment as a separate layer, for example provided by the debugging/development envionment.
How can I give a name to a new variable or object using a string variable?
For example: After I compile the program, I enter the text "a_name", press [Enter] and then a vaiable or object with the name "a_name" gets declared. Another example: I enter the text "a_name", press [Enter] and then the variable called "a_name" shows it's value.
Are there any special Libraries for this, that have to be downloaded? Or are there ones that are included in the compilers files? If there are libraries that have to be downloaded, which are the easiest to understand and use? I'm using Visual C++, but with the Libraries Iostream, Math, String, e.t.c. copied from the DevC++ compiler.
You can't add "variables" to a program once it has been compiled. You
can get more or less the same effect, however, by using std::map, with
a string as the key type.
You will, of course, have to decide what type the new variable should
have, so you know what type to map it to. If there may be more than one type, something like boost::variant might be useful. (Note that unlike the set of names, the set of possible types must be completely defined at compile-time.)
As far as I know you can't. Variable names are set up on compile time and not on run time. C++ is not interpreted (like Perl, Python or JavaScript) thus it can't evaluate expressions on run time. C++ is ol' school.
I suggest you using arrays or C++ list/map classes to try to simulate this behavior.
You can't declare variables like that, what you may do however is use a map where the key of the map is the name of the variable you would like to refer to, and the value in the map having that key, is the value of the variable.
std::map<std::string, std::string> variables;
Obviously the value could be any type, and not just a string like I have used here, you can use double, int, bool or whatever suits your need, or if you need different types you might even use Boost variant as James Kanze suggested, or any other similar class.
Read more about maps here: http://www.sgi.com/tech/stl/Map.html and here: http://www.cplusplus.com/reference/stl/map/
You can use any kind of map, but a map using a sort of hashing to store the key might be your best bet. STL hash_map: http://www.sgi.com/tech/stl/hash_map.html
So basically what you are trying to do is include an interpreted language into your C++ program.
There are many languages that support being embedded into a C++ program Lua, JavaScript, Python to mention a few.
Is it possible to convert strings into variables(and vise versa) by doing something like:
makeVariable("int", "count");
or
string fruit;
cin >> fruit; // user inputs "apple"
makeVariable(fruit, "a green round object");
and then be able to just access it by doing something like:
cout << apple; //a green round object
Thanks in advance!
No, this is not possible. This sort of functionality is common in scripting languages like Ruby and Python, but C++ works very differently from those. In C++ we try to do as much of the program's work as we can at compile time. Sometimes we can do things at runtime, and even then good C++ programmers will find a way to do the work as early as compile time.
If you know you're going to create a variable then create it right away:
int count;
What you might not know ahead of time is the variable's value, so you can defer that for runtime:
std::cin >> count;
If you know you're going to need a collection of variables but not precisely how many of them then create a map or a vector:
std::vector<int> counts;
Remember that the name of a variable is nothing but a name — a way for you to refer to the variable later. In C++ it is not possible nor useful to postpone assigning the name of the variable at runtime. All that would do is make your code more complicated and your program slower.
You can use a map.
map<string, int> numbers;
numbers["count"] = 6;
cout << numbers["count"];
Beginning programmers ask this question regarding every language. There are a group of computer languages for which the answer to this question is "yes". These are dynamic, interactive languages, like BASIC, Lisp, Ruby, Python. But think about it: Variable names only exist in code, for the convenience of the programmer. It only makes sense to define a new variable while the program runs if there's a person to then subsequently type the name of the variable in new code. This is true for interactive language environment, and not true for compiled languages like C++ or Java. In C++, by the time the program runs, and the imaginary new variable would be created, there's no one around to type code that would use that new variable.
What you really want instead is the ability to associate a name with an object at runtime, so that code -- not people -- can use that name to find the object. As other people have already pointed out, the map feature of C++'s standard library gives you that ability.
You might want to look at C++ map.
No. C++ is statically typed, and this goes against that whole paradigm.
I have seen this type of functionality implemented before by storing variables in an stl map.
At least for the (vice versa) there is a possibility with the preprocessor statement stringify #. See this answer on how to convert a C++ variable name into an string.
well i guess u cannot make dynamics variables but u can use some function to write a new variable and its value in any external text file and access its value from that file where ever it is needed (u can also remove the dynamic variable by removing it from the text file.)
theory: variables are places in memory where we store data, identified by a name, we can store data in a text file if processor doesnot allow us to store it in registers, and we can access its value by searching its identity (name of variable) int the text file, our data will be next to it.
its just an idea, it should work but i guess it will be not very simple and ur program will have to pay in terms of speed.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Dynamic source code in C++
is it possible to let the user type in a function and then run that function without using a lot of if's or a huge switch?
It is not possible to execute arbitrary c++ code in your program, since you than need a c++ compiler inside your program. But you could try to embed Python to your program. Boost python makes this relatively easy. The user can than write a python function that is executed and can interact with the classes and functions of your program. You need to make your functions explicitely visible to python.
What ever a user types in will be text, or a string. The only way I know to have it get mapped to a function is to use if/else or switch statements. That or the cringe inducing option of mapping each of your functions to a UI widget.
The end of the story, is it's your code. You have to write, and live with it. Just be careful, your program may be wildly successful, and you may not write code anymore, and then someone else will have to maintain your code. So be nice to the maintenance programmer who may follow you, and write code that isn't too tricky to figure out.
I assume you want something like eval from php.
You can try to play with command design pattern, but I doubt it will be an easy task. Basically you need to write simple C++ interpreter.
What type of function do you mean? A C++ function? If so, then you will have to either (1)interpret it or (2)compile and execute it. Interpretation would be the more likely choice here. I'm not sure if there are libraries out there already to do this but I'd assume there are.
If you don't like mega-if's or huge switches, you may be SoL on any solution for anything ever, but then again there is seldom one perfect way to do things. Consider looking in to various logic structures and algorithms to see how to do something that would normally be the job of a 23-case switch could be done another way. Like I said initially, however, sometimes you really do just need a million nested if's to do what you want to.
No, in C++ this is not possible. C++ is a compiled language. When the program runs, the compiler doesn't need to be accessible, or even installed on the machine that runs the program.
If you want to do this in C++, you need to write your own interpreter that parses whatever the user enters.
Here is my best idea, but it is a tad memory intensive.
First, create a class, lets call it MyFuncPtr to store a union of several different types of pointers to functions and an integer to tell which type it is. Overload the () operator to call the function stored with a variable length argument list. Make sure to include some sort of run-time argument checking.
Finally create a map of strings to MyFuncPtrs. Store your functions in this map along with their names. Then all you need to do is feed the name into the [] command to get a function that can be easily called. Templates could probably be used to aid in the making of MyFuncPtr instances.
This would be the easiest if it were plain C functions and no name mangling is performed on the symbols (use extern "C" { ... })
With some platform-specific code you can get the address of a function by its name. Then you cast the address as a function pointer which you can use to call the function.
On windows you must be using GetProcAddress and dlsym on Posix compliant platforms.
In C++ is there any function that returns "true" when the variable is defined or false in vice versa. Something like this:
bool isDefined(string varName)
{
if (a variable called "varName" is defined)
return true;
else
return false;
}
C++ is not a dynamic language. Which means, that the answer is no. You know this at compile time, not runtime.
There is no such a thing in runtime as it doesn't make sense in a non-dynamic language as C++.
However you can use it inside a sizeof to test if it exists on compile time without side-effects.
(void)sizeof(variable);
That will stop compilation if var doesn't exist.
As already stated, the C++ runtime system does not support the querying of whether or not a variable is declared or not. In general a C++ binary doesn't contain information on variable symbols or their mappings to their location. Technically, this information would be available in a binary compiled with debugging information, and you could certainly query the debugging information to see if a variable name is present at a given location in code, but it would be a dirty hack at best (If you're curious to see what it might look at, I posted a terrible snippet # Call a function named in a string variable in C which calls a C function by a string using the DWARF debugging information. Doing something like this is not advised)
Microsoft has two extensions to C++ named: __if_exists and __if_not_exists. They can be useful in some cases, but they don't take string arguments.
If you really need such a functionality you can add all your variables to a set and then query that set for variable existance.
Already mentioned that C++ doesn't provide such facility.
On the other hand there are cases where the OS implement mechanisms close to isDefined(),
like the GetProcAddress Function, on Windows.
No. It's not like you have a runtime system around C++ which keeps remembers variables with names in some sort of table (meta data) and lets you access a variable through a dynamically generated string. If you want this, you have to build it yourself, for example using a std::map that maps strings to some objects.
Some compile-time mechanism would fit into the language. But I don't think that it would be any useful.
In order to achieve this first you need to implement a dynamic variable handling system, or at least find some on the internet. As previously mentioned the C++ is designed to be a native language so there are no built-in facilities to do this.
What I can suggest for the most easy solution to create a std::map with string keys storing global variables of interest with a boost::any, wxVariant or something similar, and store your variables in this map. You can make your life a bit easier with a little preprocessor directive to define a variables by their name, so you don't need to retype the name of the variable twice. Also, to make life easier I suggest to create a little inline function which access this variable map, and checks if the given string key is contained by the map.
There are implementation such a functionality in many places, the runtime property handling systems are available in different fashion, but if you need just this functionality I suggest to implement by yourself, because most of these solutions are quite general what you probably don't need.
You can make such function, but it wouldn't operate strings. You would have to send variable name. Such a function would try to add 0 to the variable. If it doesn't exists, an error would occur, so you might want to try to make exception handling with try...throw...catch . But because I'm on the phone, I don't know if this wouldn't throw an error anyways when trying to send non-existing variable to the function...