Override (#define) a C ++ reserved keyword

Is it possible to override the C ++ keyword with #define?

#ifdef int
#undef int 
#define int 2
#endif
int main(){
    //Do something with int
}

      

I can't see the result in this case, but I want to understand what's going on internally. The reason I don't have a #define is because I found that it is possible to #define the reserved keyword if you are not using a standard header file. I have also tried following code.

#include<iostream>
using namespace std;
#ifdef int
#undef int 
#endif
int main(){
    cout<<int;
}

      

But te above throws an error on the cout line.

0


source to share


4 answers


Is it possible? Yes. Is this a good style? Absolutely not.

The preprocessor doesn't know the C / C ++ keywords, it only knows about the preprocessor tokens and just does strict text replacement.



Your example fails because you are #undef

it. Once you define it, it will revert to its previous behavior.

The only valid use I know of for doing something like this is to bug the old compiler , and that compiler is no longer relevant these days.

+2


source


It technically works, but it probably won't do you much good. If you want to use the C ++ standard library, you are not allowed to define any of the keywords or any of a variety of other names according to 17.6.4.3.1 [macro.names] point 2:



A translation unit must not contain #define or #undef names lexically identical to the keywords, identifiers listed in Table 3, or the attribute designators described in 7.6.

+1


source


You can, but you shouldn't.

int

Not overridden in your examples as it is wrapped in #ifdef int

. This means "only do this if there is already a preprocessor macro called int

" and there is none.

If you just wrote #define int 2

, then all occurrences int

will be replaced with 2

; but then your code won't compile as it 2 main() {cout<<2;}

is nonsense.

#undef

will not remove the keyword from the language; it only removes preprocessor macros predefined with #define

.

0


source


If you are not using standard libraries, you are allowed to do so. In fact, the preprocessor should not distinguish between reserved and unreserved words.

However, this is probably not why you are running into problems. First of all, your examples don't do what you probably think. The error is that it is int

usually not a preprocessor-defined macro. Therefore, the directive #ifdef int

skips the next lines to the final one #endif

.

This means your second example expands to:

// stuff from iostream and possibly other headers 

int main(){
    cout<<int;
}

      

the mistake is that it cout<<int;

just isn't allowed.

0


source







All Articles