isDefined function? - c++

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...

Related

How to identify uninitialized variables in a Lua script, without running it

I'd like to be able to write some Lua code like this:
y=x+1
and be able to get the names of all variables (x and y in this case) so that I can read from/write to them in the calling C++ program. The problem is that x is uninitialized, so this chunk will not execute and therefore neither variable will appear in the globals table. My current work-around is to have the user explicitly declare that they want to initialize x externally (as well as how to initialize it), then I pre-pend the Lua script with an appropriate declaration for x, so that the final script looks like this:
x= /*some value calculated outside of the Lua script*/
y=x+1
Although this works, I'd really like to have a way to automatically list all uninitialized variables in the Lua code and present them to the user, instead of the user having to remember to explicitly declare them. A function that parses the Lua code without executing it would probably be what I want. I've tried the function luaL_loadstring, but x and y don't show up in the globals table.
Since this is a bit vague, I'll give an actual use case. My C++ code basically performs optimizations on functions, such as finding a root or a maximum. I want the user to be able to define custom functions (in the form of Lua scripts), which in general will have one or more inputs and one or more outputs. The user will define which parameters the optimizer should operate on. For example, the user may want to find the minimum of y=x^2. The way I'd like it to work is that the user writes a Lua script consisting of nothing more than y=x^2, and then tells the optimizer to vary x in order to minimize y. On each iteration of the optimizer, the current guess for x would be automatically pasted into the user script, which is then executed, and then the value of y is pulled from the Lua state to be fed back to the optimizer. This is how I have it working now, however it's a bit clumsy from a UX perspective because the user has to manually declare that x is a Lua variable. This gets tedious when there are many variables that require manual declaration. It would be much better if I could automatically scan the script and show the user a list of their undeclared variables so they could then use drag-and-drop and other GUI sugar to do the manual declaration.
Lua isn't meant to work like that. Lua/C interop is intended to be collaborative; it's not supposed to be that C can do whatever it wants.
Using your example, if you have a Lua script that is supposed to take a value from C and return that value + 1, then you spell that in Lua like this:
local x = ... --Get the first parameter to the chunk.
return x + 1 --Adds 1 to the value and returns it.
You compile this string into a Lua chunk and call it like a Lua function. You pass it the value you want to manipulate and get the return value from the Lua stack.
The idea is not that C code can just reach into a Lua script and shove data into it arbitrarily. The above chunk takes parameters from the user and provides return values to the user. That's typically how C interfaces with Lua.
Yes, you can write values to globals and have the Lua script read them, and write its "results" to globals that the external code reads. But this is not the most effective way to interact with scripts.
I'd really like to have a way to automatically list all uninitialized variables
There's no such thing in Lua as an "uninitialized variable". Not in the way that you mean.
Yes, there are globals. But whether that global has a value or not is not something the Lua script can control. A global is global after all; you can set a global variable from outside of the script (for example, see lua_setglobal). If you do, then a script that reads from it will read the value you set. But it doesn't know anything about that.
What you want is a static code analyzer/Lua linter. Take a look at Luacheck:
Luacheck is a static analyzer and a linter for Lua. Luacheck detects
various issues such as usage of undefined global variables, unused
variables, and values, accessing uninitialized variables, unreachable
code and more. Most aspects of checking are configurable: there are
options for defining custom project-related globals, for selecting set
of standard globals (version of Lua standard library), for filtering
warnings by type and name of related variables, etc. The options can
be used on the command line, put into a config or directly into
checked files as Lua comments.
There is also Lualint, and similar Lua linters for Atom, VSCode, or your fav IDE.

C++ Using a string variable to call and give names to other stuff

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.

Convert string to variable name or variable type

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.

let the user use a function in c++ [duplicate]

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.

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)?
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.