Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what will happen if #pragma push_macro without #pragma pop_macro?

with #pragma pop_macro("int")

#include <iostream>
using namespace std;
#define int double
void main()
{
    int iOne = 1;
    cout << sizeof(iOne) << endl;
#pragma push_macro("int")
#undef int
    int iTwo = 2;
    cout << sizeof(iTwo) << endl;
#pragma pop_macro("int")
}

without #pragma pop_macro("int")

#include <iostream>
using namespace std;
#define int double
void main()
{
    int iOne = 1;
    cout << sizeof(iOne) << endl;
#pragma push_macro("int")
#undef int
    int iTwo = 2;

    cout << sizeof(iTwo) << endl;
//#pragma pop_macro("int")
}

I have just tried on vs2017, nothing different.both have no warnings/errors, work fine, and have the same output:

8

4


So, my question is:

  • Why vs allows this behavior?
  • Is it UB?
like image 317
Chen Li Avatar asked Oct 24 '25 09:10

Chen Li


1 Answers

very rougly speaking, push_macro means "store the current definition of the macro", pop_macro means "restore the saved definition of the macro".

Both commands have meaning in the scope of current translation unit (i.e, current compiled cpp file and including headers).

So, if you don't call pop_macro, simply the definition of the macro will not be restored, which is perfectly allowed and doesn't imply UB.

The pop_macro you put at the end of sample "With pop_macro" will actually have no effect, since there is no code following it that will be compiled

Note that we are talking about something happening at compile time, not at runtime

like image 143
Gian Paolo Avatar answered Oct 26 '25 00:10

Gian Paolo