If statement in a nested loop logic - if-statement

I am struggling with some logic. I have a nested for loop with an if statement inside.
foreach(object in list)
foreach(otherObject in otherList)
if(object.name == otherObject.name)
foo();
break;
else
bar();
This will do bar() everytime the if statement is false. How can I do bar() only if foo() is never done? Apologies if this a repeated question, which it probably is...

You could just use a flag:
did_foo = false;
foreach(object in list)
foreach(otherObject in otherList)
if(object.name == otherObject.name)
foo();
did_foo = true;
break;
if (!did_foo)
bar();

Related

how can I allow a method parameter to be null

I'm new to c++, and coming from c#;
in c# to achieve my intended goal I would simply do this
public void MyMethod(int? value) {
if(value is null) {
// Do something
} else {
// Do something else
}
}
how might I achieve this result, if possible in c++?
You can do this with std::optional.
void MyMethod(const std::optional<int>& option) {
if(option.has_value()) {
// Do something with the int option.value()
} else {
// Do something else with no value.
}
}
std::nullopt is what you pass when no value is desired. MyMethod(std::nullopt);
Or if you want to be able to omit the argument entirely and say MyMethod() then you can make the argument default to std::nullopt.
void MyMethod(const std::optional<int>& option = std::nullopt) {
This sounds like a job for overloading:
void f() {
// do something for no argument
}
void f(int i) {
// do something with I
}

C++ execute function without if check each time

Lets say I have a bool variable(global or local) & a function which is present. The function should execute only when the bool variable is true. Since this function is repeated many times & I need a way to execute this function without performing if the bool variable is true everytime.
function();
bool executeFun = true;
if(executeFun){
function();
}
..
if(executeFun){
function();
}
.. Need to execute function() without checking bool each time.
Thanks :)
Wrap it in another function.
auto perhaps = executeFun ? function : +[](){};
perhaps();
perhaps();
perhaps();
You could use a function pointer that you set after having checked the condition:
#include <iostream>
using func_t = void(*)();
int main() {
func_t p = []{};
p(); // does nothing
if(true) p = []{ std::cout << "doing something\n"; };
p(); // does something
}
Can you move the bool check inside the function?
void function();
bool executeFun = true;
void function() {
if (!executeFun) return;
...
}
...
function();
...
function();

How do I create a pipeline of functions so that functions run one after another?

I want to create classes where each class is associated with some function. I want to stack these functions in series such that one function runs after another in a user defined order. I am new to C++ so correct me wherever my syntax is wrong.
#include<iostream>
using namespace std;
class Function
{
public:
virtual void setSuccessor(Function *) = 0;
virtual void Start(int value) = 0;
};
class Prime:public Function
{
public:
Prime()
{
successor=NULL;
}
Function *successor;
void setSuccessor(Function *f)
{
//if a successor is not declared then assign successor.
//else if a successor is already defined then set the new function as the successor of the successor.
if (successor == NULL)
successor = f;
else
successor->setSuccessor(f);
}
void Start(int value)
{
//prime function
cout<<"I am Prime Function\n";
//if successor !=null
// call successor
if(successor!=NULL)
successor->Start(value);
}
};
class Even:public Function
{
public:
Even()
{
successor=NULL;
}
Function *successor;
void setSuccessor(Function *f)
{
if (successor == NULL)
successor = f;
else
successor->setSuccessor(f);
}
void Start(int value)
{
//prime function
cout<<"I am Even Function\n";
//if successor !=null
// call successor
if(successor!=NULL)
successor->Start(value);
}
};
class Pipeline
{
public:
Function *function;
void addToPipe(Function* function)
{
if(this->function==NULL)
this->function=function;
else
function->setSuccessor(function);
}
void start(int value)
{
function->Start(value);
}
};
int main()
{
Pipeline pipe;
pipe.addToPipe(new Prime());
pipe.addToPipe(new Even());
pipe.start(5);
}
In this program I have stacked Prime first then Even. I want that my function prime starts then Even starts. Since no other function is added so it should stop after Even. This program has runtime errors. Please help me detect them
Found two flaws in your program (could be reasoned to be simple typos):
Pipeline::function is never initialized, so it has some garbage value, which causes undefined behaviour when dereferencing it (for example a crash). Simply initialize it to NULL or preferably nullptr like you do in the other two classes.
In Pipeline::addToPipe you forgot a this:
void addToPipe(Function* function)
{
if(this->function==NULL)
this->function=function;
else
function->setSuccessor(function); // Calls setSuccessor on the local variable!!
}
With those two fixed I received the (expected) output
I am Prime Function
I am Even Function
You may use standard library templates for this and avoid writing your own classes. For example,
# include <iostream>
void prime(int) { cout << "Prime" << endl; }
void even(int) { cout << "Even" << endl; }
...
#include <functional>
#include <vector>
std::vector<std::function<void(int)>> pipeline;
pipeline.push_back(prime);
pipeline.push_back(even);
...
for (const auto& f : pipeline) f();
Note that it seems odd to have functions named "prime" and "even" that return void.

Is it possible to change behavior of function based on scope?

I would like to create something similar to rust unsafe scope in C++.
The idea is that I have some functions performing number of checks. For example:
void check() {
if (...)
throw exception(...);
}
void foo() {
check();
// do some work
}
Now, I want to be able to call function foo() with or (in different context) without performing those checks. Ideally it would look like this:
foo(); // call foo and perform checks
unsafe {
foo(); // call foo without checks
}
My question is, is it possible to achieve something like this in compile time? Is it possible to somehow check (or act differently) from check function in what scope it is called?
I came up only with a runtime solution: to wrap it in some lambda:
unsafe([&] {
foo();
});
where unsafe is implemented as follows:
void unsafe(std::function<void()> f)
{
thread_local_flag = unsafe;
f();
thread_local_flag = safe;
}
check() function would just check for the thread_local flag and perform checks only when it is set to safe.
🤔
namespace detail_unsafe {
thread_local int current_depth;
struct unsafe_guard {
unsafe_guard() { ++current_depth; }
~unsafe_guard() { --current_depth; }
unsafe_guard(unsafe_guard const &) = delete;
unsafe_guard &operator = (unsafe_guard const &) = delete;
};
}
#define unsafe \
if(::detail_unsafe::unsafe_guard _ug; false) {} else
bool currently_unsafe() {
return detail_unsafe::current_depth > 0;
}
See it live on Coliru. Also, please don't actually define unsafe as a macro...
is it possible to achieve something like this in compile time?
Not the way you presented. Making foo a template function might give you equivalent results, though:
enum class CallType // find a better name yourself...
{
SAFE,
UNSAFE,
};
template <CallType Type = CallType::SAFE>
void foo()
{
if constexpr(Type != CallType::UNSAFE)
{
if (...)
throw ...;
}
// do some work
}
You might call it like:
foo();
foo<CallType::UNSAFE>();
Disliking templates?
Simple approach (thanks, #VTT):
void check(); // no template any more
void foo_unsafe()
{
// do some work
}
inline void foo()
{
check();
foo_unsafe();
}
Or selecting via parameter (this pattern exists in standard library, too):
struct Unsafe
{
};
inline Unsafe unsafe;
void check();
void foo(Unsafe)
{
// do some work
}
inline void foo()
{
check();
foo(unsafe);
}
Edit:
Well, in the example I presented I could do that, but in general, I can call some other function bar inside unsafe which in turn calls foo. And I don't want to specialize bar and possible other methods.
Unter this constraint, the template variant might be the closest you can get to at compile time; you don't have to specialise all the functions, but you'd need to make templates from:
template <CallType Type = CallType::SAFE>
void bar()
{
// do some other work
foo<Type>(); // just call with template parameter
// yet some further work
}
I would simply use a RAII type to toggle the unsafe flag inside a scope as such:
thread_local bool unsafe_flag = false;
/// RAII Type that toggles the flag on while it's alive
/// Possibly add a reference counter so it can be used nested
struct unsafe_scope
{
constexpr unsafe_scope() { unsafe_flag = true; }
~unsafe_scope() { unsafe_flag = false; }
};
/// Gets a value from a pointer
int get_value(int* ptr)
{
if ( unsafe_flag )
{
if ( ptr == nullptr ) { return 0; }
}
return *ptr;
}
int main()
{
int* x = nullptr;
//return get_value(x); // Doesn't perform the check
{
unsafe_scope cur_scope;
return get_value(x); // Performs the check
}
}
In order to make it nested I would add a reference counter like this:
/// RAII Type that toggles the flag on while it's alive
struct unsafe_scope
{
thread_local static size_t ref_count;
constexpr unsafe_scope()
{
unsafe_flag = true;
ref_count++;
}
~unsafe_scope()
{
ref_count--;
if ( ref_count == 0 ) { unsafe_flag = false; }
}
};
/// In source file
thread_local size_t unsafe_scope::ref_count = 0;
The ref_count doesn't need to be atomic since it's thread_local
Now I don't think there's a way to achieve the syntax you wanted with the unsafe before the scope, but if you put it right after the scope as such it should be about the same:
{ unsafe_scope cur_scope;
return get_value(x); // Performs the check
}
Edit:
I've now noticed Quentin's answer is also a RAII type, just with slightly different semantics, instead of having a global thread_local flag a function just returns if the reference counter is bigger than 0. Also the macro achieves the exact syntax you wanted, although it's also possible with this unsafe_scope by modifying his macro like this:
#define unsafe\
if (unsafe_scope cur_scope; false) {} else
His method uses C++17's if initializer, which lets you initiates a variable in the if statement, but the variable is still initialized in the else block, so it only gets destroyed after the else scope if over.

Trigger event on return in C++

I want to execute some function right before the return of another function. The issue is that there are multiple returns and I don't want to copy-paste my call before each of them. Is there a more elegant way of doing this?
void f()
{
//do something
if ( blabla )
return;
//do something else
return;
//bla bla
}
I want to call g() before the function returns.
struct DoSomethingOnReturn {
~DoSomethingOnReturn() {
std::cout << "just before return" << std::endl;
}
};
...
void func() {
DoSomethingOnReturn a;
if(1 > 2) return;
}
There are some ways to do this.
One would be to use boost::scope_exit or use a struct and do your work in the destructor.
I dislike the preprocessor syntax of boost and I am too lazy to write struct so I prefer using a boost::shared_ptr or on newer compilers a std::shared_ptr. Like this:
std::shared_ptr<void>(nullptr, [](void*){ /* do your stuff here*/ });
This is often a sign that instead of trying to artificially do something before every return, you should try to refactor your function into single-exit form. Then it's super easy to do your extra step because...there's only one return.
I think try-finally statements will do what you want.
void f()
{
__try
{
//do something
if ( blabla )
return;
//do something else
return;
//bla bla
}
__finally
{
g();
}
}
The try-finally statement is a Microsoft extension to the C and C++
languages that enables target applications to guarantee execution of
cleanup code when execution of a block of code is interrupted. Cleanup
consists of such tasks as deallocating memory, closing files, and
releasing file handles. The try-finally statement is especially useful
for routines that have several places where a check is made for an
error that could cause premature return from the routine.
Quoted from msdn.
#define RETURN_IT g(); \
return;
void f()
{
//do something
if ( blabla )
RETURN_IT;
//do something else
RETURN_IT;
//bla bla
}
Simple, although I do kind of like loki's suggestion
For this kind of thing, you could simply use a boolean. That way you don't have too many if/else statements:
void f()
{
//do something
done = false;
if ( blabla )
done = true;
//do something else
if (!done) {
// some code
done = true;
}
if (!done) {
// some other code
done = true;
}
return;
}
void f()
{
//do something
if ( blabla )
return;
//do something else
return;
//bla bla
}
void f_callg()
{
f();
g();
}
If there is no access to where f() is called from
void f_copy_of_old()
{
//do something
if ( blabla )
return;
//do something else
return;
//bla bla
}
void f()
{
f_copy_of_old();
g();
}
int g() {
// blah
return 0;
}
void f() {
// do something
if (blabla)
return g();
// do something else
return g();
}