The question is: Could you please help me understand better the RAII macro in C language(not c++) using only the resources i supply at the bottom of this question? I am trying to analyse it in my mind so as to understand what it says and how it makes sense(it does not make sense in my mind). The syntax is hard. The focus of the question is: i have trouble reading and understanding the weird syntax and its implementation in C language. For instance i can easily read, understand and analyse(it makes sense to me) the following swap macro:
#define myswap(type,A,B) {type _z; _z = (A); (A) = (B); (B) = _z;}
(the following passage is lifted from the book: Understanding C pointers)
In C language the GNU compiler provides a nonstandard extension to support RAII.
The GNU extension uses a macro called RAII_VARIABLE. It declares a variable and associates with the variable:
- A type
- A function to execute when the variable is created
A function to execute when the variable goes out of scope
The macro is shown below:
#define RAII_VARIABLE(vartype,varname,initval,dtor) \ void _dtor_ ## varname (vartype * v) { dtor(*v); } \ vartype varname __attribute__((cleanup(_dtor_ ## varname))) = (initval)
Example:
void raiiExample() { RAII_VARIABLE(char*, name, (char*)malloc(32), free); strcpy(name,"RAII Example"); printf("%s\n",name); } int main(void){ raiiExample(); }
When this function is executed, the string “RAII_Example” will be displayed. Similar results can be achieved without using the GNU extension.
std::string
will do what you example does, and without any non-portable extensions. – Blus-E
option; for example,gcc -E my_source.c
. – Mesocarp(char*)
cast is not needed inRAII_VARIABLE(char*, name, (char*)malloc(32), free);
Removing it reduces code noise. – Meshach