Inline return to original caller - c++

I have a C++ wrapper to wrap a library for C. The wrapper frequently performs a variable check. I would like to break this down into an inline function call, but I would like the inline function to return to the original caller if the check fails.
For the sake of simplicity, we'll call the library I wrapped libraryA and we'll call the library's object objectA.
Here's what I'm doing:
#define LIBRARY_A_NULL_PARAMETER -1
#define LIBRARY_A_CAST_FAIL -2
signed int wrapper_doSomething(void *ptrVariable){
libraryA::objectA *objA;
/* variable checks */
if(!ptrVariable){
return LIBRARY_A_NULL_PARAMETER;
}
try{
objA = (libraryA::objectA *)ptrVariable;
}catch(...){
return LIBRARY_A_CAST_FAIL;
}
/* perform the rest of the function */
}
Because this check is performed in nearly every function, I'd like to simplify this to something like:
#define LIBRARY_A_NULL_PARAMETER -1
#define LIBRARY_A_CAST_FAIL -2
inline signed int checkVariable(void *ptrVariable, libraryA::objectA **assignTo){
if(!ptrVariable){
return LIBRARY_A_NULL_PARAMETER;
}
try{
*assignTo = (libraryA::objectA *)ptrVariable;
return 1; // success
}catch(...){
return LIBRARY_A_CAST_FAIL;
}
}
signed int wrapper_doSomething(void *ptrVariable){
libraryA::objectA *objA;
/* variable checks */
checkVariable(ptrVariable, &objA);
/* perform the rest of the function */
}
I'd like the checkVariable() function to return back to the original caller if the check fails.
Because all error codes are negative numbers, I can of course say:
int response = checkVariable(ptrVariable, &objA);
if(response < 0){
return response;
}
This would handle the situation, but I would like to remove the if-statement, if possible, and thus reduce the variable check to exactly one line. Is this achievable?
I plan on looking into macros, but I have not used macros before, so I'm not sure if they could accomplish this either.
EDIT:
Per Anton's answer, would a macro definition like this suffice:
#define CHECK_VARIABLE(ptrVariable, objA) \
{\
if(!ptrVariable) return LIBRARY_A_NULL_PARAMETER;\
try{\
*objA = (libraryA::objectA *)ptrVariable;\
}catch(...){\
return LIBRARY_A_CAST_FAIL;\
}\
}
I would then call it as:
CHECK_VARIABLE(ptrVariable, &objA);

Without exceptions you have to use macros. Given you have checkVariable() function, the macro can look like this:
#define CHECK_VARIABLE(ptrVariable, objA) \
{\
int response = checkVariable((ptrVariable), &(objA));\
if (response < 0)\
return response;\
}

As you are using exceptions already, you can use them for that purpose, too:
inline signed int checkVariable(void *ptrVariable, libraryA::objectA **assignTo) {
if (!ptrVariable) {
throw LIBRARY_A_NULL_PARAMETER;
}
try {
*assignTo = (libraryA::objectA *)ptrVariable;
return 1; // success
} catch(...) {
throw LIBRARY_A_CAST_FAIL;
}
}
You can write the wrapper_doSomething function exactly as desired but the caller of that function has to catch the exception that is passed along.

Related

cannot overload functions distinguished by return type alone but it is not a real mistake

I have different variants of some function, that are choosed by preprocessor definition
#if defined(V2)
bool getAICoord(TTT_Game& game) {
//
// 4x4 field
//
return false;
}
#elif defined(V3)
bool getAICoord(TTT_Game& game) {
//
// renju field
//
return false;
}
#else // V1
bool getAICoord(TTT_Game& game) {
// some code
return false;
}
#endif
And it compiles well, but IntelliSense gives me error
cannot overload functions distinguished by return type alone
I know, that it is not perfect, but is there any way to exclude this one function from its checklist or something like this?
You could workaround this error by only typing the function signature once and using the preprocessor definitions on the body of the function; e.g.
bool getAICoord(TTT_Game& game) {
#if defined(V2)
//
// 4x4 field
//
return false;
#elif defined(V3)
//
// renju field
//
return false;
#else // V1
// some code
return false;
#endif
}
Preprocessor macros notoriously confuse IDEs, as they are pure text transformation of the code, instead of being part of the language itself.
Instead of using macros, if constexpr lets you do conditional compilation as part of the language itself instead of doing it as a preprocessor step:
This has a number of advantages:
It confuses IDEs a lot less.
All code paths get syntactical validation, even when excluded.
constexpr int kVersion = SOME_DEFINE;
bool getAICoord(TTT_Game& game) {
if constexpr(kVersion == 3) {
//...
} else if constexpr(kVersion == 2) {
//...
} else {
//...
}
}

Macro for while loop with deferred function call

I would like to construct a macro where a predefined function (here simulated by "call fcn here") is called every time when the loop ends an iteration. This is what I have so far, which actually works.
Is there shorter way, eventually with more macro magic to write such behavior?
#define MYWHILE(condition) \
while( \
[]()->bool { \
static bool called = false; \
if(called) std::cout<<"call fcn here"<<std::endl; \
called=true; return true;}() \
&& condition)
This macro should than be used on several places in the code to ensure than nobody forgets to call the function when they write busy waiting loops.
A typical example would be:
while(true){
bool b = foo();
if(b){
break;
}
ros::spinOnce();
}
Where oft the call ros::spinOnce() is forgotten, so I simply replace the sample code with:
MYWHILE(true){
bool b = foo();
if(b){
break;
}
}
Pure C - Code would also be fine.
Rather than a complicated looking while loop, you can package up what you need into a for loop:
for (; condition; fcn())
The function will be called at the end of every iteration, before reevaluating the condition.
I would like to construct a macro where a predefined function (here
simulated by "call fcn here") is called every time when the loop ends
an iteration, but NOT at the first time.
Since your provided code and your question conflict, it is not clear what behavior you want. To implement the above, I would recommend not using macros at all and simply writing your code as:
do {
if(!condition)
break;
// More code here
} while(fcn());
What's wrong with just:
while(!foo()) {
ros::spinOnce();
}
That is logically equivalent to:
while(true){
bool b = foo();
if(b){
break;
}
ros::spinOnce();
}
Yet far simpler than:
MYWHILE(true){
bool b = foo();
if(b){
break;
}
}

How to use macro as function pointer?

How can I use macros as function pointers? I have no idea to solve this. I created a sketch (doesn't work, full of syntax errors) to show what I try to accomplish. Please help!
#define D0_OUT(x) (x/1024*100) //I want to use this for Pin0 calculation
#define D1_OUT(x) (x*1024) //I want to use this for Pin1 calculation
struct Pin {
CalcMethod *calcMethod; //int methodName(int x) { return MACRO(x); }
Pin(CalcMethod *calcMethodParam) {
calcMethod = calcMethodParam;
}
int calc(int x) {
return calcMethod(x);
}
};
#define PIN_COUNT 2
Pin *pins[PIN_COUNT];
void start() {
pins[0] = new Pin(D0_OUT); //use the D0_OUT macro to calculate
pins[1] = new Pin(D1_OUT); //use the D1_OUT macro to calculate
int pin0CalcResult=pins[0]->calc(5); // =5/1024*100
int pin1CalcResult=pins[1]->calc(6); // =6*1024
}
Macros are handled by the preprocessor. They don't exist in the compiled code, therefore there is no pointer.
There is one rule you should follow in modern code and that rule is "don't use macros for furnctions". Macros for functions are a relict that still has some good uses but they are very rare.
Just declare a normal function
int do_out(int x) {
return x / 1024 * 100;
}
Also see "static const" vs "#define" vs "enum"
You can, but not advisable, use macros as named lambdas. Thus
#define D0_OUT [](int x) { return x / 1024 * 100; }
#define D1_OUT [](auto x) { return x * 1024; }
and it should work.
D0_OUT example usable in C++11 and D1_OUT usable with C++14.
I know this is an old thread..
Assuming that you cannot just change the macro to be a function. Maybe it is part of a driver of library somewhere and you need to pass it into another function for some reason like unit testing. You can just wrap the macro within your .c file where you want to use it.
So this:
#define D0_OUT(x) (x/1024*100) //I want to use this for Pin0 calculation
becomes:
static int D0_OUT_wrapper(int x)
{
return D0_OUT(x);
}
So wrapper goes in like normal:
pins[0] = new Pin(D0_OUT_wrapper);
If you have full control of the code you are writing then just don't use macros.

Skip code without using state variable, using goto envisaged

I have a code which has parts that mustn't be executed if there was an error before in the code. I actually use a bool variable called EndProg that, if set to true, will instruct the program to avoid executing some parts of code.
My problem is that I don't want to use this method and I'd prefer to use goto instead because it will make the program jump to the cleanup part and avoid checking EndProg value multiple times.
The other problem is that I've read on many pages on StackOverflow and other websites that using goto is considered a bad practice and that it can make a code more difficult to read or create errors.
My code is simple enough and I will need to use just one label so I doubt that this will create problems; but I would like to know if there are other ways to do what I want without creating functions to do cleanup tasks or using return (because, for example, I will need to write the cleanup code several times) and I also don't want to write the same big cleanup code in multiple places and then use return or do something else.
I don't want to increase the number of lines of code nor use return nor use a lot of if nor check the value of a state variable. What would you recommend ?
Here's a piece of code :
bool EndProg=false;
/*
Lot of code that can set EndProg to true
*/
ClassType ClassName;
if(!EndProg && LoadConf(&ConfFilePath,&ClassName)==0)
{
int fildes=-1;
if(ClassName.abc) // bool
{
if(ClassName.FilePath==0) // char *
{
ClassName.FilePath=new(std::nothrow) char[9]();
if(ClassName.FilePath!=0)strcpy(ClassName.FilePath,"file.ext");
else EndProg=true;
}
if(!EndProg && mkfifo(ClassName.FilePath,S_IRUSR | S_IWUSR)==-1)
{
if(errno==EEXIST)
{
/* EEXIST is returned if the file already exists
We continue, later we will try to open this file */
}
else EndProg=true;
}
if(!EndProg && (fildes=open(ClassName.FilePath,O_RDWR))==-1)EndProg=true;
}
/*
Lot of code that will check if EndProg == true
*/
}
delete[] ClassName.FilePath;
delete[] ConfFilePath;
What I would like to do is :
bool EndProg=false;
/*
Lot of code that can set EndProg to true
*/
ClassType ClassName;
if(LoadConf(&ConfFilePath,&ClassName)==0)
{
int fildes=-1;
if(ClassName.abc) // bool
{
if(ClassName.FilePath==0) // char *
{
ClassName.FilePath=new(std::nothrow) char[9]();
if(ClassName.FilePath==0)goto cleanup;
strcpy(ClassName.FilePath,"file.ext");
}
if(mkfifo(ClassName.FilePath,S_IRUSR | S_IWUSR)==-1)
{
if(errno==EEXIST)
{
/* EEXIST is returned if the file already exists
We continue, later we will try to open this file */
}
else goto cleanup;
}
if((fildes=open(ClassName.FilePath,O_RDWR))==-1)goto cleanup;
}
/*
Lot of code that will check if EndProg == true
*/
}
cleanup:
delete[] ClassName.FilePath;
delete[] ConfFilePath;
As you can see it isn't difficult to understand and even if searching the label can be a problem for someone, it isn't for me; and I don't plan to make the code public.
Update :
I decided to using exceptions and it works for some parts of my original code. But I doubt this will be easy to implement in more complex parts. Thanks for your answers.
Since you've tagged this question c++ as well I'd go with using exceptions and a try catch block.
You can find a lot of useful information about the subject on SO and on other websites:
Here is a very basic tutorial.
And here is a nice and basic FAQ that might help you as well.
Basically there's nothing to fear, exceptions are not cryptic and in fact make more sense when you get the hang of it. Because basically this concept enables you to achieve exactly what you want:
Several pitfalls that can be handled by the same error handling code.
Edit:
For example if I'd move the mkfifo etc. into a function (in general creating a function for each well defined logical block is clearer and more readable) and have something like
This is just a sketch to give you a general idea:
#include <exception>
functionThatDoesMakeFifo(...){
// check which ever conditions you want to check after mkfifo
// if one of them goes wrong just do:
throw std::exception();
}
// this is inside your function:
ClassType ClassName;
try{
ClassName.FilePath = new char[9](); // even though I'd use a string...
.
.
. // rest of the code
} catch(std::exception &e){
delete [] ClassName.FilePath;
delete [] ConfFilePath;
ClassName.FilePath = NULL; // not mandatory just my habit
ConfFilePath = NULL;
}
I would try with something like Scope Guards or BOOST_SCOPE_EXIT (C++) or its C++11 analogue:
template<class F>
struct ScopeExit
{
ScopeExit(F f) : f(f) {}
~ScopeExit() { f(); }
F f;
};
template<class F>
ScopeExit<F> MakeScopeExit(F f) { return ScopeExit<F>(f); }
#define STRING_JOIN2(arg1, arg2) DO_STRING_JOIN2(arg1, arg2)
#define DO_STRING_JOIN2(arg1, arg2) arg1 ## arg2
#define SCOPE_EXIT(code) \
auto STRING_JOIN2(scope_exit_, __LINE__) = MakeScopeExit([=](){code;})
bool myfunct()
{
ClassType ClassName;
ClassName.FilePath = 0;
ConfFilePath = 0;
SCOPE_EXIT(delete [] ClassName.FilePath; delete [] ConfFilePath; );
if (LoadConf(&ConfFilePath,&ClassName) == 0)
{
int fildes=-1;
if(ClassName.abc) // bool
{
if(ClassName.FilePath==0) // char *
{
ClassName.FilePath=new(std::nothrow) char[9]();
if(ClassName.FilePath==0) return false;
strcpy(ClassName.FilePath,"file.ext");
}
if(mkfifo(ClassName.FilePath,S_IRUSR | S_IWUSR)==-1)
{
if (errno==EEXIST)
{
/* EEXIST is returned if the file already exists
We continue, later we will try to open this file */
}
else return false;
}
if((fildes=open(ClassName.FilePath,O_RDWR))==-1) return false;
}
/*
Lot of code that will check if EndProg == true
*/
}
return true;
}
I'm using return but the cleanup code is just in one place.
Anyway ClassName should take care of cleaning up its own resources in the destructor.
There is a little trick I have seen before that might help you solve this, although I am personally not a fan of tricks, it might be appropriate for what you require.
while (true)
{
if(ClassName.FilePath==0) // char *
{
ClassName.FilePath=new(std::nothrow) char[9]();
if(ClassName.FilePath==0) break;
strcpy(ClassName.FilePath,"file.ext");
}
if(mkfifo(ClassName.FilePath,S_IRUSR | S_IWUSR)==-1)
{
if(errno==EEXIST)
{
/* EEXIST is returned if the file already exists
We continue, later we will try to open this file */
}
else break;
}
if((fildes=open(ClassName.FilePath,O_RDWR))==-1) break;
/*
Lot of code that will check if EndProg == true
*/
break;
}
delete[] ClassName.FilePath;
delete[] ConfFilePath;
But again I am not condoning this as a graceful solution, I personally would re-write your code and break it down into something more readable.
But then again I don't write functions containing hundreds of lines either.
I may get downvoted for this, but I think that limited use of goto in C is not evil. Particularly, what you are talking about is quite acceptable: branching forward to clean up code on errors. I'd suggest that you limit this to a single target label per routine.
What people hate (justifiably) is the old fastion spaghetti code with goto's jumping all over the place.

how to return multiple error codes from C++ function

What is a good way to return success or one or more error codes from a C++ function?
I have this member function called save(), which saves to each of the member variables, there are at least ten of these member variables that are saved-to, for the call to save(), I want to find out if the call failed, and if so, on which member variable (some are hard failures, some are soft).
You can either return an object that has multiple error fields or you can use 'out'parameters.
How you do this depends on your design and what exactly you are trying to return back. A common scenario is when you need to report back a status code along with a message of sorts. This is sometimes done where the function returns the status code as the return value and then returns the message status via an 'out' parameter.
If you are simply returning a set of 'codes', it might make more sense to construct a struct type and return that. In that case, I would be prone to pass it in as an out parameter and have the method internally update it instead of allocating a new one each time.
Are you planning on doing this once or many times?
I know this doesn't really answer your question, but...
In C++ you should use exceptions instead of returning error codes. Error codes are most commonly used by libraries which don't want to force the library user to use a particular error handling convention, but in C++, we already have stdexcept. Of course, there might be reasons you don't use exceptions, such as if you're writing embedded code or kernel extensions.
I usually use a boost::tuple:
typedef boost::tuple<int,int> return_value;
return_value r = my_function();
int first_value = boost::get<0>( r );
int second_valud = boost::get<1>( r );
EDIT
You can also use boost::tie to extract the values from a tuple:
boost::tie( first_value, second_value ) = r;
The simplest way to return two values is with the std::pair<> template:
I would use a bitset if you're intention is to purely return error states. e.g.
const bitset<10> a_not_set(1);
const bitset<10> b_not_set(2);
const bitset<10> c_not_set(4);
...
bitset<10> foo(T& a, T& b, T& c, ...)
{
bitset<10> error_code = 0;
...
if ( /* a can't be set */ )
{
error_code |= a_not_set;
}
...
if ( /* b can't be set */ )
{
error_code |= b_not_set;
}
...
// etc etc
return error_code;
}
bitset<10> err = foo(a, b, c, ... );
if (err && a_not_set)
{
// Blah.
}
You need to return them as output parameters:
bool function(int& error1, int& error2, stringx& errorText, int& error3);
You can use an integer with bit manipulation (aka flags).
I probably try to throw an exception first but it depends on your coding paradigm. Please check some books or articles about reasons why c++ exception handling might be better.
If I really need to stick to retrun-error-code style, I would define a eunm type for specifying errors with bit operations..
enum error
{
NO_ERROR = 0,
MEMBER_0_NOT_SAVED = 1,
MEMBER_1_NOT_SAVED = 1 << 1,
MEMBER_2_NOT_SAVED = 1 << 2,
// etc..
};
int save()
{
int ret = NO_ERROR;
// fail to save member_0
ret |= MEMBER_0_NOT_SAVED;
// fail to save member_1
ret |= MEMBER_1_NOT_SAVED;
// ....
return ret;
}
int main(void)
{
int ret = save();
if( ret == NO_ERROR)
{
// good.
}
else
{
if(ret & MEMBER_0_NOT_SAVED)
{
// do something
}
if(ret & MEMBER_1_NOT_SAVED)
{
// do something
}
// check the other errors...
}
}
This is just a rough example. It's better to put this into a class or use a namespace.
I am not familiar with the internals and constrains of your project, but if possible, try to use exceptions instead of error codes.
The reasons are listed here, at C++ FAQ lite, and they conclude with:
So compared to error reporting via return-codes and if, using try / catch / throw is likely to result in code that has fewer bugs, is less expensive to develop, and has faster time-to-market.