Macro or #define the 'struct' keyword

Aug 7, 2022 at 4:19am
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 Aug 7, 2022 at 4:24am
Aug 7, 2022 at 5:08am
I believe that you're not technically allowed to
#define struct X
But you can certainly
#define X struct
Aug 7, 2022 at 9:49am
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....
Aug 7, 2022 at 1:22pm
I can't advise enough against doing this. Macros that redefine C++ to a new language make an unreadable mess.
Aug 7, 2022 at 2:13pm
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
Aug 7, 2022 at 3:52pm
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'.
Aug 7, 2022 at 5:32pm
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)
Aug 7, 2022 at 11:05pm
Thanks for the info guys. I decided to just go for typedef.
Topic archived. No new replies allowed.