void main()
{
int xyz = 123; // original value
{ // code block starts
xyz++;
if(xyz < 1000)
xyz = 1;
} // code block ends
int original_value = xyz; // should be 123
}
void main()
{
int xyz = 123; // original value
MACRO_NAME(xyz = 123) // the macro takes the code code that should be executed at the end of the block.
{ // code block starts
xyz++;
if(xyz < 1000)
xyz = 1;
} // code block ends << how to make the macro execute the "xyz = 123" statement?
int original_value = xyz; // should be 123
}
Only the first main() works.
I think the comments explain the issue.
It doesn’t need to be a macro but to me it just sounds like a classical “macro-needed” case.
By the way, there’s the BOOST_FOREACH macro/library and I think it does the exact same thing I’m trying to achieve but it’s too complex for me to find the essence of what I need.
From its introductory manual page, an example:
#include <string>
#include <iostream>
#include <boost/foreach.hpp>
int main()
{
std::string hello( "Hello, world!" );
BOOST_FOREACH( char ch, hello )
{
std::cout << ch;
}
return 0;
}
The cleanest way to do this is probably to use an RAII container to reset the value:
used as:
When the block ends, the destructor will be called, resetting the object to the specified value.
If you really want to use a macro, as long as it is a relatively simple expression, you can do this using a for-block:
which can be turned into a macro:
used as:
I don’t really think the macro approach is a good idea; I’d probably find it confusing were I to see this in production source code.