How to avoid coding same code twice in (if, if else) statement, when the code has to run if one is true? - if-statement

Consider this pseudo code:
if(p){
foo()
bar1()
}
if else(q){
foo()
bar2()
}
Is there a way of avoiding writing the call for function foo() twice? I could write:
if(p||q){
foo()
}
...
But is that the only solution?

Keep in mind there is no problem with calling the same function from both if and else, one of the reasons we do function it's reusability and that is proper way to reuse it.
One of the options to avoid calling the same function:
if(p||q){
foo();
if (p){
bar1();
}
else {
bar2();
}
}
Also remember that readability of the code is VERY important and although it's opinion based, I think you way is clearer

Related

please solve this memory leak problem in c++

class A
{
public:
unique_ptr<int> m_pM;
A() { m_pM = make_unique<int>(5); };
~A() { };
public:
void loop() { while (1) {}; } // it means just activating some works. for simplifying
};
int main()
{
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
A a;
a.loop(); // if i use force quit while activating this function, it causes memory leak
}
is there any way to avoid memory leak when i use force quit while activating this program?
a.loop() is an infinite loop so everything after that is unreachable, so the compiler is within its right to remove all code after the call to a.loop(). See the compiler explorer for proof.
I believe that outside of some niche and very rare scenarios truly infinite loops like the one you wrote here are pretty useless, since they literally mean “loop indefinitely”. So what’s the compiler supposed to do? In some sense it just postpones the destruction of your object until some infinite time in the future.
What you usually do is use break inside such loop and break when some condition is met. A simplified example: https://godbolt.org/z/sxr7eG4W1
Here you can see the unique_ptr::default_delete in the disassembly and also see that the compiler is actually checking the condition inside the loop.
Note: extern volatile is used to ensure the compiler doesn’t optimise away the flag, since it’s a simplified example and the compiler is smart enough to figure out that the flag is not changed. In real code I’d advice against using volatile. Just check for the stop condition. That’s it.

C++: compile-time checking for matching pairs of function calls?

I have a timer class I use to time blocks of code. Essentially something like this:
timer.start();
////do something
timer.end();
I am looking for a compile-time way to ensure that both the start and end call exist, and are within scope. Even hacky methods.
Here is one example of what I mean...this would generate a compile-time error if "end()" is called, but not "start()", due to the way a hidden variable "foo" is initialized.
#define start_macro bool foo = false; timer.start();
#define end_macro foo = true; timer.end();
//start_macro
////do something
end_macro //generates error because start_macro not called, thus foo not declared
But obviously the application of that method is limited because it generates no error if end() is the function not called.
Are there any clever ways I can ensure both functions are called, in order and in scope, at compile-time? I'm not interested in any run-time checking methods...I'd like a faster way to catch missing calls.
Unfortunaley there is no general solution. You would need to tell the compiler somehow, what are the matching functions. And, you never know, in which scope the closing function should be. So, rather difficult to impossible.
The better approach would be to use a wrapper class with constructor/destructor solution. The constructor would start the timer and the destrcutor would stop it. But that is runtime . . .
Another solution would be to write macro, which injects the code between timer start and stop, between such statements. But really not nice and anyway, marcros are not recommended. There could be also a template approach, trying to mimick that.
But for this to judge you need to specify more requirements.
You can use RAII, define a class wrapper, for example ScopedTimer, it's constructor calls start() and the destructor calls end(). Make your Timer::start() and Timer::end() protected, and make ScopedTimer as a friend of Timer, so that only ScopedTimer can calls to them.
There is no runtime checking. And there is no compile time checking either. It just makes it impossible to write code that calls one of the functions but not the other.
class ScopedTimer {
public:
explicit ScopedTimer(Timer *tm)
: tm_(tm) {
this->tm_->start();
}
~ScopedTimer() { this->tm_->stop(); }
protected:
Timer* tm;
};
// Your code will be like this:
{ // This pair of braces defines the scope that you want to measure.
ScopedTimer st(&timer);
////do something
}
Just as Shawn pointed out in his comment. To make sure timer has started, you simple put start of timer in constructor and stop in destructor. I used this method while making measurements for my project.
class Timer {
public:
Clock clock;
Timer() { clock.start(); }
~Timer()
{
clock.stop();
saveMeasurements();
}
private:
void saveMeasurements(); //save measurements to file
}

How to end the program from a function which is called in another function (C++)

I have a loop of functions that I called like the code I wrote below and I want at some point to end the program.The problem is that I don't want to use exit function because I have data allocated dynamic also I could use an if in every function and exit one by one but I think will make the code a lot harder to understand and I have more than 3 functions like this.
void c()
{
//code
//I want to exit the program
}
void b()
{
c();
//code
}
void a()
{
b();
//code
}
int main()
{
a();
return 0;
}
Thanks for the help.
You can return from all functions all the way to main (nicest).
You can call some variant of exit.
You can throw an exception.
You can use setjmp/longjmp to jump to the end of main (please don't).
You can crash the application (by calling abort, raise(SIGKILL) or similar).
I can't think of more options, but there may well be some...
Inside your functions used std::unique_ptr wherever you need dynamic allocations.
Then modify :
int main()
{
try
{
a();
}
catch(...)
{ /*... */}
return 0;
}
Then inside any of the deep functions, throw can be used, and std::unique_ptr will release the resources auto-magically.

Good program design/best practice to avoid multiple redundant checks (eg. in C++) [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 4 years ago.
Improve this question
Suppose I have some functions (eg. method1() and method2()), and each of these functions should only be performed if a some condition(s) are met (for this simplistic example, call this a check against a boolean). To isolate the conditional check, I place the check inside each function - eg
void method1()
{
if (bDoSomething) {
doSomething1();
doSomething2();
}
}
void method2()
{
if (bDoSomething) {
doSomething1();
doSomething3();
}
}
However, the doSomethingN() functions can also be called on their own, outside of method1() and method2(), so I then add the conditional check into each doSomethingN() function- eg.
void doSomething1() {
if (bDoSomething) {
doWork1();
}
}
Also, suppose method1() and method2() can be called from within the same function - eg.
void func1() {
method1();
method2();
}
This results in multiple checks for the same condition when calling func1(), method1() or method2(). What would be a better way of doing this to avoid the multiple checks ?
Are there any good resources on how best to design/structure a program to minimise this kind of thing ?
Depending on the concrete details of your issue.. One thing you could do is to put the checks within the doSomething functions.
void doSomething1() {
if(!bDoSomething) return;
....
}
You don't need to check the conditions in the outer functions, Just call the appropriate functions and they will execute if needed. You could still leave it in for self-documentation purposes.
It is also possible that your code is a lot more convoluted than is needed. To diagnose that you need more details and the big picture.
p.s You can try my style of checking, i.e return-if-negative, rather than process-if-positive, this might make the code a little cleaner sometimes, but reducing the indentation level.
Suppose you have two classes: Private and Captain. Lets use them in such a way that Captains command Privates. What Captains want, Privates do. Let's have an illustration:
void Captain::HaveSomethingDone() {
if(AmIAtAnAdvantage()) {
for(Private& p : m_privates) {
p.Attack();
}
}
else if(IsSituationStalemate()) {
for(Private& p : m_privates) {
p.Hold();
}
}
else if(IsALosingBattle()) {
for(Private& p : m_privates) {
p.Retreat();
}
}
}
In the above example, the Privates do unconditionally what the Captain wants because the Captain knows what it's doing. In this way we have clear(er) separation of concerns.
Another one, now for methods. Take this as an example:
void DoSomething() {
if(ShouldPrint()) {
Print();
}
if(ShouldCleanUp()) {
CleanUp();
}
// ...
}
In the above example, DoSomething() knows what it should do. It is the one who decides what it should do. The Print() and CleanUp() methods therefore should unconditionally do what it's meant to do. Print() prints. CleanUp() cleans up.
Now contemplate.
I think the best way to avoid multiple conditional checks would be implement State design pattern in your code. This design pattern just allows you to use code as State machine, meaning depending upon the state of your object state you can call desired method. you can get more information over here http://en.wikipedia.org/wiki/State_pattern
Well, I guess your check is pretty heavy, otherwise I would not worry about double call, because your code will be much CLEANER.
I have two things in mind:
Caching the first check result somewhere in your class.
Making caller object, which could be created only when your condition is true.
Something like that:
class ConditionalCaller
{
public:
void Method1();
void Method2();
};
class YourClass
{
public:
ConditionalCaller* GetCaller()
{
if (CanGetCaller())
return new ConditionalCaller();
return NULL;
}
bool CanGetCaller();
};
There are a few different cases:
method1 and method2 are private, you can control where they are called and you can guarantee that all pre conditions are checked. In this case you can avoid these tests in these methods.
method1 and method2 are public and you document that as a precondition several conditions have to be met (like in containers in std).
method1 amd method2 check their precondition and respond accordingly (throwing and exception, do nothing, ...).
you create checked and unchecked versions of your methods (mixing other variants) and distinguish them via different names *_checked or additional parameters (like in notthrow new).
But remember Scott Meyers: Make Interfaces Easy to Use Correctly and Hard to Use Incorrectly.
So you have make your decision and document it.

longjmp and RAII

So I have a library (not written by me) which unfortunately uses abort() to deal with certain errors. At the application level, these errors are recoverable so I would like to handle them instead of the user seeing a crash. So I end up writing code like this:
static jmp_buf abort_buffer;
static void abort_handler(int) {
longjmp(abort_buffer, 1); // perhaps siglongjmp if available..
}
int function(int x, int y) {
struct sigaction new_sa;
struct sigaction old_sa;
sigemptyset(&new_sa.sa_mask);
new_sa.sa_handler = abort_handler;
sigaction(SIGABRT, &new_sa, &old_sa);
if(setjmp(abort_buffer)) {
sigaction(SIGABRT, &old_sa, 0);
return -1
}
// attempt to do some work here
int result = f(x, y); // may call abort!
sigaction(SIGABRT, &old_sa, 0);
return result;
}
Not very elegant code. Since this pattern ends up having to be repeated in a few spots of the code, I would like to simplify it a little and possibly wrap it in a reusable object. My first attempt involves using RAII to handle the setup/teardown of the signal handler (needs to be done because each function needs different error handling). So I came up with this:
template <int N>
struct signal_guard {
signal_guard(void (*f)(int)) {
sigemptyset(&new_sa.sa_mask);
new_sa.sa_handler = f;
sigaction(N, &new_sa, &old_sa);
}
~signal_guard() {
sigaction(N, &old_sa, 0);
}
private:
struct sigaction new_sa;
struct sigaction old_sa;
};
static jmp_buf abort_buffer;
static void abort_handler(int) {
longjmp(abort_buffer, 1);
}
int function(int x, int y) {
signal_guard<SIGABRT> sig_guard(abort_handler);
if(setjmp(abort_buffer)) {
return -1;
}
return f(x, y);
}
Certainly the body of function is much simpler and more clear this way, but this morning a thought occurred to me. Is this guaranteed to work? Here's my thoughts:
No variables are volatile or change between calls to setjmp/longjmp.
I am longjmping to a location in the same stack frame as the setjmp and returning normally, so I am allowing the code to execute the cleanup code that the compiler emitted at the exit points of the function.
It appears to work as expected.
But I still get the feeling that this is likely undefined behavior. What do you guys think?
I assume that f is in a third party library/app, because otherwise you could just fix it to not call abort. Given that, and that RAII may or may not reliably produce the right results on all platforms/compilers, you have a few options.
Create a tiny shared object that defines abort and LD_PRELOAD it. Then you control what happens on abort, and NOT in a signal handler.
Run f within a subprocess. Then you just check the return code and if it failed try again with updated inputs.
Instead of using the RAII, just call your original function from multiple call points and let it manually do the setup/teardown explicitly. It still eliminates the copy-paste in that case.
I actually like your solution, and have coded something similar in test harnesses to check that a target function assert()s as expected.
I can't see any reason for this code to invoke undefined behaviour. The C Standard seems to bless it: handlers resulting from an abort() are exempted from the restriction on calling library functions from a handler. (Caveat: this is 7.14.1.1(5) of C99 - sadly, I don't have a copy of C90, the version referenced by the C++ Standard).
C++03 adds a further restriction: If any automatic objects would be destroyed by a thrown exception transferring control to another (destination) point in the program, then a call to longjmp(jbuf, val) at the throw point that transfers control to the same (destination) point has undefined behavior. I'm supposing that your statement that 'No variables are volatile or change between calls to setjmp/longjmp' includes instantiating any automatic C++ objects. (I guess this is some legacy C library?).
Nor is POSIX async signal safety (or lack thereof) an issue - abort() generates its SIGABRT synchronously with program execution.
The biggest concern would be corrupting the global state of the 3rd party code: it's unlikely that the author will take pains to get the state consistent before an abort(). But, if you're correct that no variables change, then this isn't a problem.
If someone with a better understanding of the standardese can prove me wrong, I'd appreciate the enlightenment.