Title: Overloaded operators in C via macros with type notification
Tags: c;macros;operator-overloading
Question: The C preprocessor can't be used to overload operators, since it doesn't know the types of a and b in the expression "a+b", see this question.
However, what about giving it the type, something like this:
out = (a*b+b*n) x c : {a,b,c-&gt;vector3, n-&gt;float};
Which would be preprocessed into:
vector3 out = cross(add(dot(a,b), mult(b,n)),c);
This work around, useful when migrating the codebase to C++ or interfacing C and C++ is not worth the trouble, is no less verbose. However, the expression left of the : is much easier to read.
Is such a solution feasible?
Comment: I really really doubt that something like this would be accepted somewhere except experimental/code-obfuscation areas. Think headache to debug such things - overkill

Comment: This would be preprocessed... by what?

Comment: Targeting a homebrew half-baked macro processor, or targeting a real language like C++? That's a hard dilemma...

Comment: "C++ brings up portability problems". Your solution brings **unknown** problems. I'll stick with gcc. You do realize you cannot use standard macros and have to conjure up your own macro processor, right?

Comment: Some macro that hopefully wouldn't be too hard to write.

Comment: @n.m: Your right that not invented here is a common disease. But C++ brings up portability problems in my case. No, I won't try any fancy metaprogramming, simply using the verbose way is fine. This is more for me to get a feel for the capability of macros.

Comment: @n.m. Yes that's partly why I won't do it. Just not worth it. The normal way of spelling out "add" and "cross" is fine.

Here is the accepted answer: This is not possible with C preprocessor, and I can simply prove it by simply listing all the preprocessor directives.
#include (copy-pastes the content of the file)
#define (macros)
#if, #else,#elif, #ifdef, #ifndef (conditional compilation)
#line (changing value of __LINE__ and __FILE__)
#error (enforce a compilation error)
#pragma (compiler-dependent functionality)
# (empty directive, does nothing)
The one functionality you're interested in, macros, only work for identifiers:
#define MAX(a,b) replacement
#define VALUE replacement
+, *, :, {, } are not identifiers.


{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 7, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2014:00:06/21/14', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<c><macros><operator-overloading>', 'Title': 'Overloaded operators in C via macros with type notification', 'ViewCount': 834, 'id': 24341628, 'user_AboutMe': '', 'user_AccountId': 179512.0, 'user_DisplayName': 'Kevin Kostlan', 'user_Reputation': 3099.0, 'user_Views': 273.0, 'user_id': 412234.0}}