Instead of doing the following everytime
start();
// some code here
stop();
I would like to define some sort of macro which makes it possible to write like:
startstop()
{
//code here
}
Is it possible in C++?
C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...
What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.
Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.
Because a and b and c , so it's name is C. C came out of Ken Thompson's Unix project at AT&T. He originally wrote Unix in assembly language. He wrote a language in assembly called B that ran on Unix, and was a subset of an existing language called BCPL.
You can do something very close using a small C++ helper class.
class StartStopper {
public:
StartStopper() { start(); }
~StartStopper() { stop(); }
};
Then in your code:
{
StartStopper ss;
// code here
}
When execution enters the block and constructs the ss
variable, the start()
function will be called. When execution leaves the block, the StartStopper
destructor will be automatically called and will then call stop()
.
The idiomatic way of doing this in C++ is called Resource Acquisition Is Initialization, or shortly RAII. In addition to providing what you want, it also has the added benefit of being exception safe: the stop
function will be called even if your code throws an exception.
Define a guard struct:
struct startstop_guard
{
startstop_guard()
{
start();
}
~startstop_guard()
{
stop();
}
};
and then rewrite your code this way:
{
startstop_guard g;
// your code
}
The guard's destructor (and thus the stop
function) will be called automatically at the end of the enclosing block.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With