Macro for while loop with deferred function call - c++

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;
}
}

Related

Macro that inserts code into control structure

I have a waitUntil macro defined as
#define waitUntil(condition) while(!(condition)) delay(10);
Occasionally, I need code like updating a variable in that while loop. Given the definition of the macro, it is not usable, and I have to revert back to writing the while-loop and delay.
while(!condition){
counter++;
delay(10);
}
Is there a way to re-write the macro to allow code in the loop body?
A better example is #define FOR(count) for(int i = 0; i < count; i++)
This is ok, because
FOR(5){
//body
}
expands into
for(int i = 0; i < 5; i++){
//body
}
I can't do this with the while loop since that delay must be present.
EDIT:
Thank you for the answers. Yes, I understand the preference for functions over macros in C++. Also, I get the standard for all-caps, but this is a very small codebase, and only 4 of us will really interact with it and we all know waitUntil is a macro.
While passing a function to it would work, I was looking for a way that didn't need the code to be passed into the macro. If that is the only option, it's ok; then a direct while loop is probably best.
Something that should do what I want is:
#define waitUntil(condition) while(!(condition)){ delay(10);
Which should then be able to be used as
waitUntil(counter > 4)
counter++;
}
But this has clear issues.
You don't really need a macro for this. Here is a function template implementation:
template<typename C, typename F>
void waitUntilAndDo(C condition, F func) {
while(!condition()) {
func();
delay(10);
}
}
which can be called, e.g. as
waitUntilAndDo([&]{ return counter < 100; }, [&]{ counter++; });
You can also just do this with a single function argument of course:
template<typename C>
void waitUntil(C condition) {
while(!condition()) {
delay(10);
}
}
called as e.g.
waitUntil([&]{
/* something to do */
return /* condition */;
});
with the caveat that this executes /* something to do */ even if the loop condition is false from the beginning (which could of course also be resolved in the condition lambda, but wouldn't look nice).
Although just writing out the loop is probably clearer in any case.
If you specifically want a macro that uses a while loop internally and can still execute arbitrary code followed by a delay then you need to put the delay into the while loop condition:
#define waitUntil(condition) while(delay(10),!(condition))
The comma operator make delay(10) execute first, followed by !(condition) (left to right executrion) - the last expression determines the result of the whole expression.
You can try it here: https://www.onlinegdb.com/uQqle2qxo
The downside is that delay(10) is executed at least once - even if the condition is already met. If you use a for loop the condition can be checked before the loop executes and the delay can happen after the arbitrary code:
#define waitUntil(condition) for(;!(condition);delay(10))
You can try it here: https://www.onlinegdb.com/LeK3OPv9Y

Is it possible to go to higher level scope condition's else in C++?

I have the exact same lines of code in the both do something section so I want to merge the two sections into one.
But I don't want to create a separate function for do something.
Is there a way to go to condition A's else when it reaches condition B's else?
if (conditionA)
{
//some code here
if (conditionB)
{
}
else
{
//do something
}
}
else
{
//do something
}
Jumping through code is definitely discouraged, if you really want to minimize the code then the only thing you can do is to rearrange the flow to better suit your needs, eg:
if (conditionA)
{
some code
if (conditionB)
do something else
}
if (!conditionA || !conditionB)
do something
If you (as indicated in the comments) don't want to create a function that you need to pass 6 arguments, then you could use a lambda like this:
const auto do_something = [&] { /* do stuff with captured reference variables */ };
if (conditionA) {
// some code here
if (conditionB) {
// stuff
} else {
do_something();
}
} else {
do_something();
}
if-else is really just syntactic sugar for gotos. You can use an explicit goto here:
if (conditionA)
{
//some code here
if (conditionB)
{
}
else goto do_something;
}
else
{
do_something: /*...*/;
}
This could/should be faster than adding another if check.
Alternatively, you can use an inlinable static function. There should be no performance difference if it does get inlined (and it won't piss off gotos-considered-harmful dogmatists).
(In my opinion, an occasional, clean, downward goto won't harm the readability of your code, but the dogmatism against gotos is strong (as evidenced by downvotes on this answer :D)).
Given that there is no code after //do something, You can use a pattern such as
if (conditionA)
{
//some code here
if (conditionB)
{
//do something else
return;
}
}
//do something
However a clearer pattern would be to encapsulate //do something into a separate function.
To answer what you are asking in the title: Yes, it is possible. There are at least three ways I can think of:
Using goto's (highly discouraged)
Putting "do something" code in a function (perhaps inline for performance) (may result to cleaner code)
Reformatting your if/else statements and merging your conditions as demonstrated in other answers. The rationale is to group the code segments that appear twice (by unifying logical expressions using operators). (I would prefer this way if the code is not that large or if it has high dependencies with other parts)
I would change conditions and rearrange the code a bit.
if (!conditionA || (conditionA && !conditionB))
do_something();
else if (conditionA) {
some_code_here();
if (conditionB)
// Your `if(conditionB)` section goes here.
}
Another possibility (one I think is often preferable) is to combine the conditions into a single variable, then use a case statement for the combinations:
unsigned cond = ConditionA | (ConditionB << 1);
enum { neither, A, B, both};
switch (cond) {
neither: // Both A and B were false;
A: // Only A was true;
B: // Only B was true;
both: // both A and B were true;
}
Then when you want the same code executed for two conditions, you just let normal switch fall-through happen.
You can wrap it up into cthulhu loop and use break:
for(;;) // executed only once
{
if (conditionA)
{
//some code here
if(conditionB)
{
// some more code here
break; // for(;;)
}
}
//do something
break; // for(;;)
}
I think this is more alegant then use for(;;) (VTT answer, which I upwoted)
do
{
if(conditionA )
{
//some code here
if(conditionB)
{
//some code
break;
}
}
// do something
} while(0);

C++ create a function similar to while, if, or for

Think about this code in C/C++:
bool cond = true;
while(cond){
std::cout << "cond is currently true!";
}
Is it possible to create a function that can be called like this?
myFunction(some_parameters_here){
//Code to execute, maybe use it for callbacks
myOtherFunction();
anotherFunction();
}
I know you can use function pointers and lambda functions, but I was wondering if you can. I'm pretty sure there is a way to do so, because how would while() exist?
while(condition) { expression } is not a function but a control structure / a separate language construct; it executes expression again and again as long as condition evaluates to true (i.e. something != 0).
an function definition of the form void myFunction(int someParameter) { expression }, in contrast, is executed only when it is called by another function.
Hope it helps a bit;
Caution: this solution comes without the guarantee that your code reviewer will like it.
We can use a trick similar to the one Alexandrescu uses for his SCOPE_EXIT macro (awesome one-hour conference, this bit is at 18:00).
The gist of it: a clever macro and a dismembered lambda.
namespace myFunction_detail {
struct Header {
// Data from the construct's header
};
template <class F>
void operator * (Header &&header, F &&body) {
// Do something with the header and the body
}
}
#define myPrefix_myFunction(a, b, c) \
myFunction_detail::Header{a, b, c} * [&]
Using it as follows:
myPrefix_myFunction(foo, bar, baz) {
}; // Yes, we need the semicolon because the whole thing is a single statement :/
... reconstitutes a complete lambda after macro expansion, and lands into myFunction_detail::operator* with acess to foo, bar, baz, and the body of the construct.

Inline return to original caller

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.

C/C++ optimizing away checks to see if a function has already been run before

Let's say you have a function in C/C++, that behaves a certain way the first time it runs. And then, all other times it behaves another way (see below for example). After it runs the first time, the if statement becomes redundant and could be optimized away if speed is important. Is there any way to make this optimization?
bool val = true;
void function1() {
if (val == true) {
// do something
val = false;
}
else {
// do other stuff, val is never set to true again
}
}
gcc has a builtin function that let you inform the implementation about branch prediction:
__builtin_expect
http://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html
For example in your case:
bool val = true;
void function1()
{
if (__builtin_expect(val, 0)) {
// do something
val = false;
}
else {
// do other stuff, val is never set to true again
}
}
You should only make the change if you're certain that it truly is a bottleneck. With branch-prediction, the if statement is probably instant, since it's a very predictable pattern.
That said, you can use callbacks:
#include <iostream>
using namespace std;
typedef void (*FunPtr) (void);
FunPtr method;
void subsequentRun()
{
std::cout << "subsequent call" << std::endl;
}
void firstRun()
{
std::cout << "first run" << std::endl;
method = subsequentRun;
}
int main()
{
method = firstRun;
method();
method();
method();
}
produces the output:
first run subsequent call subsequent call
You could use a function pointer but then it will require an indirect call in any case:
void (*yourFunction)(void) = &firstCall;
void firstCall() {
..
yourFunction = &otherCalls;
}
void otherCalls() {
..
}
void main()
{
yourFunction();
}
One possible method is to compile two different versions of the function (this can be done from a single function in the source with templates), and use a function pointer or object to decide at runtime. However, the pointer overhead will likely outweigh any potential gains unless your function is really expensive.
You could use a static member variable instead of a global variable..
Or, if the code you're running the first time changes something for all future uses (eg, opening a file?), you could use that change as a check to determine whether or not to run the code (ie, check if the file is open). This would save you the extra variable. Also, it might help with error checking - if for some reason the initial change is be unchanged by another operation (eg, the file is on removable media that is removed improperly), your check could try to re-do the change.
A compiler can only optimize what is known at compile time.
In your case, the value of val is only known at runtime, so it can't be optimized.
The if test is very quick, you shouldn't worry about optimizing it.
If you'd like to make the code a little bit cleaner you could make the variable local to the function using static:
void function() {
static bool firstRun = true;
if (firstRun) {
firstRun = false;
...
}
else {
...
}
}
On entering the function for the first time, firstRun would be true, and it would persist so each time the function is called, the firstRun variable will be the same instance as the ones before it (and will be false each subsequent time).
This could be used well with #ouah's solution.
Compilers like g++ (and I'm sure msvc) support generating profile data upon a first run, then using that data to better guess what branches are most likely to be followed, and optimizing accordingly. If you're using gcc, look at the -fprofile-generate option.
The expected behavior is that the compiler will optimize that if statement such that the else will be ordered first, thus avoiding the jmp operation on all your subsequent calls, making it pretty much as fast as if it wern't there, especially if you return somewhere in that else (thus avoiding having to jump past the 'if' statements)
One way to make this optimization is to split the function in two. Instead of:
void function1()
{
if (val == true) {
// do something
val = false;
} else {
// do other stuff
}
}
Do this:
void function1()
{
// do something
}
void function2()
{
// do other stuff
}
One thing you can do is put the logic into the constructor of an object, which is then defined static. If such a static object occurs in a block scope, the constructor is run the fist time that an execution of that scope takes place. The once-only check is emitted by the compiler.
You can also put static objects at file scope, and then they are initialized before main is called.
I'm giving this answer because perhaps you're not making effective use of C++ classes.
(Regarding C/C++, there is no such language. There is C and there is C++. Are you working in C that has to also compile as C++ (sometimes called, unofficially, "Clean C"), or are you really working in C++?)
What is "Clean C" and how does it differ from standard C?
To remain compiler INDEPENDENT you can code the parts of if() in one function and else{} in another. almost all compilers optimize the if() else{} - so, once the most LIKELY being the else{} - hence code the occasional executable code in if() and the rest in a separate function that's called in else