Avoiding non symbolic constants in Qt - c++

One thing that often comes up in code reviews I participate in is 'magic numbers' inline in code as being a bad thing.
The preference is that a symbol be assigned somewhere.
Now what I am working with at the moment is in the QT sdk. The class member QButtonGroup.checkedId() will return -1 as a magic number to signify that there are no radio buttons in the group selected.
And if I write something like
if ( buttongroup->checkedId() == -1 )
{
//yadda yadda
}
it will come up in the code review.
While certainly I can define a const static int symbol to give me that -1, I'd much rather use something in the Qt namespace if it has a relevant constant defined.
Is there such a symbol already defined??

Code reviews are about your code not the code of 3rd party libraries so you can't and shouldn't deal with it. Qt doesn't have any named entity to compare against so you have to compare the resulting code against -1. There is a bright side about it, though: -1 is a broadly understood magic number so there should not be any misunderstanding — it is used in many different languages and libraries. However bad it is it is here and we have to live with it.

No such symbol is predefined; you would have to define it yourself.

Related

Importing constants out of C++ headers instead of hardcoding them: extending .net controls?

I've been researching how to extend .net controls to have more freedom to do the same things you can do with the regular windows API in C++ in a VB program. For example, if you want to add week numbers to a calendar control, you'll have to manually import the DLL and extend the control's class, calling internal windows functions.
I've found various topics on how people handle this, and I'm not quite happy with the 'canonical method'. To be honest, I think it's a pretty bad paradigm to use.
These internal windows functions use pointers to set magic properties.
First, I find it rather strange that a pointer, which its system-dependent value size, is being abused to hold something that isn't a memory location but a value, but that aside: these pointers are also used to set which attribute is being set.
For example, (leaving out all the boilerplate necessary to link up the code), changing the first day of the week to Tuesday would use this code:
Private Const MCM_FIRST As Int32 = &H1000
Private Const DTM_FIRST As Int32 = &H1000
Private Const DTM_GETMONTHCAL As Int32 = (DTM_FIRST + 8)
Private Const MCM_SETFIRSTDAYOFWEEK As Int32 = (MCM_FIRST + 15)
Dim hMonthView As IntPtr =
SendMessage(Me.Handle, DTM_GETMONTHCAL, IntPtr.Zero, IntPtr.Zero)
Call SendMessage(hMonthView, MCM_SETFIRSTDAYOFWEEK, 0&, 1&)
So the magic values of 0x1008 and 0x1015 is what my question is about in this code.
First off, this is a rather strange way of working: these values aren't documented anywhere as far as I know other than the examples. What if I need a property where there happens to not be an internet tutorial on so far? Where/how do I find the value of MCM_<ARBITRARY_VALUE_HERE> in general?
Note: I mean the latter question in the broad, general sense: not applying to just the specific calendar control the example is about, but really any windows control. I can already google up the specific C++ header file by name (e.g. for the example it's defined in Commctrl.h: it's just that that piece of information is rather useless if I don't know the idiomatic way of how to pull something like that out of the C++ header into the VB code.
Secondly... these values are defined in headers somewhere. Is it not possible to import the values from the proper header? This way the program will stay working in the (admittedly unlikely) scenario where the DLL is changed by re-compiling it.
One approach for this back for VB6 was to prepare a TLB file with constants, function declarations, etc. of the Win32 API, and then reference that in the VB6 program. The TLB didn't provide COM objects, it was just a convenient way of packaging up all the declarations as though they were in (what we now think of as) an assembly.
As far as I can think, that approach should still work perfectly well today in .NET through "COM" interop. You can just as easily reference the TLB in a C# or VB project and thereby access its contents.
The book Hardcore Visual Basic by Bruce McKinney included a disk with a prepared TLB for this purpose, and this seems to still be available today:
http://vb.mvps.org/hardweb/mckinney2a.htm
I don't know how comprehensive this was at the time, nor if it is really still up to date. At the very least it seems instructive in how to prepare a TLB for this type of approach.
The following page also provides a description of this approach with some additional explanation an examples (too long to copy in here).
http://www.brainbell.com/tutors/Visual_Basic/newfile156.html

# operator not defined

I am reading through a .cpp trying to figure out some things and came across code like this:
some_function()
{
CustomClass some_sort_of_list;
string sample;
if (sample != "") {
some_sort_of_list = #BOING(args);
}
}
Has anyone seen the # operator before, or is it just #define used somewhere in one of the header files? I do not have access to the headers.
Since #Captain Obvlious mentioned early versions of Visual C++, I will look there to see what is going on...
PS: I should mention also, in case it's not obvious enough, that the names have been changed since I don't know if I have the license to share this source. The main issue is the #SOMETHING.
PPS: the comments are in Japanese, and I have limited access to the original authors.
That's not standard C++, it's not even legal as a #define since they're not permitted to start with #.
It's probably something that gets run through a pre-processor of some sort, like Oracle's Pro*C compiler which can turn EXEC SQL into C function calls, before passing to an actual C compiler.
Your best bet would be to think about the environment that this code runs in, such as "is it an internationalised application where #GEN may retrieve a locale-specific string for output?".
And, since, you mention that the comments are in Japanese, you should at least give Google Translate a try. It can sometimes result in hilarity for complex phrases but it may well give you a needed clue.

Which is more memory/performance efficient for static error strings, or are there alternatives?

I would like an opinion on what is the best way to handle static error strings in C++. I am currently using a number of constant char pointers, but they get unwieldy, and they are scatter every where in my code. Also should I be using static constant char pointers for these strings?
I was thinking about defines, hash tables, and INI files using the SimpleIni class for cross-platform compatibility. The project is an always running web server.
I would like to use error numbers or names to refer to them logically.
I am using the global space and methods contained in namespaced classes if that helps. The code is exported to C because of the environment if that helps as well.
Thanks
There are several things in tension here, so let me please enumerate them:
centralization / modularity: it is normal to think about centralizing things, as it allows to easily check for the kind of error one should expect and recover an error from an approximate souvenir etc... however modularity asks that each module be able to introduce its new errors
error may happen during dynamic initialization (unless you ban code from running then, not easy to check), to circumvent the lifetime issue, it is better to only rely on objects that will be initialized during static initialization (this is the case for string literals, for example)
In general, the simplest thing I have seen was to use some integral constant to identify an error and then have a table on the side in which you could retrieve other information (potentially a lot of it). For example, Clang uses this system for its diagnosis. You can avoid repeating yourself by using the preprocessor at your advantage.
Use such a header:
#define MYMODULE_ERROR_LIST \
ERROR(Code, "description") \
...
#define ERROR(Code, Desc) Code,
class enum ErrorCode: unsigned {
MYMODULE_ERROR_List
NumberOfElements
};
#undef ERROR
struct Error {
ErrorCode code;
char const* description;
};
Error const& error(ErrorCode ec);
And a simple source file to locate the array:
#define ERROR(Code, Desc) { Code, Desc },
Error const ErrorsArray[] = {
MYMODULE_ERROR_LIST
{ErrorCode::NumberOfElements, 0}
};
Error const& error(ErrorCode const ec) {
assert(unsigned(ec) < unsigned(ErrorCode::NumberOfElements) &&
"The error code must have been corrupted.");
return ErrorsArray[ec];
} // error
Note: the price of defining the macro in the header is that the slightest change of wording in a description implies a recompilation of all the code depending on the enum. Personally, my stuff builds much faster than its tested, so I don't care much.
This is quite an efficient scheme. As it respects DRY (Don't Repeat Yourself) it also ensures that the code-description mapping is accurate. The ERROR macro can be tweaked to have more information than just a description too (category, etc...). As long as the Error type is_trivially_constructible, the array can be initialized statically which avoids lifetime issues.
Unfortunately though, the enum is not so good at modularity; and having each module sporting its own enum can soon get boring when it comes to dealing uniformly with the errors (the Error struct could use an unsigned code;).
More involved mechanisms are required if you wish to get beyond a central repository, but since it seemd to suit you I'll stop at mentioning this limitation.
First of all, you can check other related questions on stackoverflow. Here you have some:
C++ Error Handling -- Good Sources of Example Code?
Exceptions and error codes: mixing them the right way
Then have a look at this great tutorial on error handling (it is a five parts tutorial, but you can access all of them from that link). This is especially interesting if you are using C++11, since it provides many more features for error handling. Alternatively you could use boost if you cannot use C++11.
You also need to consider whether you want to include support for localization. If your application may present messages to the users in different languages, it is better if you include that requirement from the very beginning in the error management too. You can check Boost.Locale for that, for instance.
I'd keep it simple, in a header:
enum ErrorCode { E_help, E_wtf, E_uhoh };
const char* errstr(ErrorCode);
Then in some .c or .cc file:
const char* error_strings[] = {
"help!",
"wtf?",
"uh-oh"
};
const char* errstr(ErrorCode e) { return error_strings[e]; }
Not a lot of detail in your question, but with what you've posted I would consider a singleton class for handling your error messages. You could create methods for accessing messages by code number or enum. Then you can implement internationalization or whatever else you need for your specific application. Also, if you do decide to use SQLite or some other file-based solution in the future, the class interface can remain intact (or be extended) minimizing impact on the rest of your code.

How local constants are stored in c++ library files

I am writing a library where I need to use some constant integers. I have declared constant int as a local variable in my c function e.g. const int test = 45325;
Now I want to hide this constant variable. What it means is, if I share this library as a .so with someone, he should not be able to find out this constant value ?
Is it possible to hide constant integers defined inside a library ? Please help
Here is my sample code
int doSomething()
{
const int abc = 23456;
int def = abc + 123;
}
doSomething is defined as local function in my cpp file. I am referring this constant for some calculations inside the same function.
If I understand right, you're not so much worried about an exported symbol (since it's a plain normal local variable, I'd not worry about that anyway), but about anyone finding out that constant at all (probably because it is an encryption key or a magic constant for a license check, or something the like).
This is something that is, in principle, impossible. Someone who has the binary code (which is necessarily the case in a library) can figure it out if he wants to. You can make it somewhat harder by calculating this value in an obscure way (but be aware of compiler optimizations), but even so this only makes it trivially harder for someone who wants to find out. It will just mean that someone won't see "mov eax, 45325" in the disassembly right away, but it probably won't keep someone busy for more than a few minutes either way.
The constant will always be contained in the library in some form, even if it is as instructions to load it into a register, for the simple reason that the library needs it at runtime to work with it.
If this is meant as some sort of a secret key, there is no good way to protect it inside the library (in fact, the harder you make it, the more people will consider it a sport to find it).
The simplest is probably to just do a wrapper class for them
struct Constants
{
static int test();
...
then you can hide the constant in the .cpp file
You can declare it as
extern const int test;
and then have it actually defined in a compilation unit somewhere (.cpp file).
You could also use a function to obtain the value.

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.