Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ #define a macro with brackets?

Tags:

c++

macros

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++?

like image 223
Rolle Avatar asked Apr 17 '09 08:04

Rolle


People also ask

What C is used for?

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 in C language?

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.

Is C language easy?

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.

Why is C named so?

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.


2 Answers

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().

like image 197
Greg Hewgill Avatar answered Sep 30 '22 02:09

Greg Hewgill


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.

like image 24
avakar Avatar answered Sep 30 '22 01:09

avakar