Reputation: 299
header1.h
#define MaxNum 10
#define MinNum 1
//similar 100 other variables defined
main.cpp
#include header1.h
main()
{
int size;
string first = "MaxNum"; //could be any of the variable name defined in header file
size = MaxNum ;
I have certain variables defined in header file. In main, depending on the value of "first" i need to set the value of "size". Is this do-able ?
Upvotes: 0
Views: 999
Reputation: 45665
I guess you want to have
size = MaxNum
if first == "MaxNum"
and
size = MinNum
if first == "MinNum"
. If the set of possible values for first
(the set of variables to choose from) is only small, you can simply put the assignment around an if
, else if
series of statements. Finally, put an else
statement to write an error message.
However, you have to hardcode every case:
if (first == "MaxNum") {
size = MaxNum;
}
else if (first == "MinNum") {
size = MinNum;
}
//...
So your code to decide the assignment to size
becomes larger as the number of variable grows. This is considered bad style and very unmaintainable as well as error-prone.
If you don't want to do this, don't use several variables in your program, but one container variable containing all these possible keys with their values. It's called associate container, and in C++ there is the type std::map
which implements such a data structure.
// Your container for the sizes (or whatever you want to call it)
std::map<std::string, int> sizes;
sizes["MinNum"] = 1;
sizes["MaxNum"] = 100;
// ... more values ...
// Accessing this container with a variable as the key:
size = sizes[first];
As you can see, accessing this container using a string variable as the key is very easy. sizes[first]
simply gives you the value in the container of which the key equals the value of the current contents of the variable first
.
A very important fact about C++ (and C) source code is that during runtime you don't have access to the names of variables. So essentially, they can be renamed without affecting your program. What you want to have (querying names of variables, enums, classes, functions, their parameters, etc.) is known as introspection or meta-programming, as you write code which operates on your code ("meta-code").
C++ doesn't provide meta-programming facilities per default (only exception I know of: typeid
, but nothing for variable names / defines). By default means, that you could hack around this limitation and include some additional step in your build process which parses your header file for these definitions and stores them in a different way accessible during runtime. But the map is the better way, believe me.
Upvotes: 3