Macro or #define the 'struct' keyword

I would like to define the struct keyword to something else or perhaps use macro to add another keyword but still is using struct.

Last edited on
I believe that you're not technically allowed to
#define struct X
But you can certainly
#define X struct
You can define struct to mean something else - as #define is part of the pre-processor which is performed prior to the compiler getting it's hands on the code.

But why would you want to? Making struct act like something else would be very confusing and not likely to make friends... Don't!

Just to be annoying:

1
2
3
4
5
6
7
8
9
10
11
#define struct class

struct  S {
	int a {};
};

int main() {
	S s;

	s.a = 1;
}


This code gives a compile error:

error C2248: 'S::a': cannot access private member declared in class 'S'

but I don't use class I hear you wail. What's going on....
I can't advise enough against doing this. Macros that redefine C++ to a new language make an unreadable mess.
You can define struct to mean something else - as #define is part of the pre-processor which is performed prior to the compiler getting it's hands on the code.

I guess it's technically not allowed if you use the standard library at all.
https://eel.is/c++draft/constraints#macro.names
You shouldn't do it at all! There's a big difference between what you can do and what you should not do! Just because you can, doesn't mean you should - especially if it's not test code!

You #define struct (or even better - class!) before a standard library include and sit back and watch the pages of compile errors that are coughed up by the compiler

defining say S to be the same as struct is one thing - defining struct to mean something else is quite different - and as they say 'beyond the pale'.
I would like to define the struct keyword to something else

Why? What are you trying to do? Explain in detail what you want to do, not your XY "solution".

use macro to add another keyword but still is using struct.

BAD idea. Using macros/#defines is very type UN-safe, and if your C++ compiler lets you mangle the language doing so will likely end up in a buttload of errors.

It looks like you want to create an alias, not overload C/C++ functionality to do something different.

There are a couple of C++ ways to define a new type alias that is type safe:

1. typedef - https://en.cppreference.com/w/cpp/language/typedef (inherited from C)

2. using - https://en.cppreference.com/w/cpp/language/type_alias (added in C++11)
Thanks for the info guys. I decided to just go for typedef.
Topic archived. No new replies allowed.