0

i'm not sure if what im talking about is an operator overloading question. is it possible to overload keywords in C++??
for example : i need to write loopOver(i=0; ;i++) instead of for(i=0;;i++) ?? is that possible in C++

and i need to have something like 2 addTo 2 instead of 2 + 2

please help thanks in advance

Georg Schölly
126k54 gold badges225 silver badges277 bronze badges
asked Dec 12, 2009 at 9:51
5
  • 1
    You could use a macro #define loopOver for #define addTo + Commented Dec 12, 2009 at 9:56
  • 2
    Do you have a hidden reason for wanting to do this? Commented Dec 12, 2009 at 9:58
  • 2
    Why do you "need to write" this? With a background you might get more helpful answers. Commented Dec 12, 2009 at 9:58
  • its just a homework . :D , no hidden reason or something . Commented Dec 12, 2009 at 10:39
  • What a bad homework assignment. Commented Dec 12, 2009 at 11:03

2 Answers 2

8

You can't do that with operator overloading (you can't change the names of the operators, only how they work).

However, evil as it is, if you don't want to change the way they work (just the names), you would be able to achieve things like this using macros:

#define loopOver for
#define addTo +

(Use macros with extreme care though - if used incorrectly they can cause hideous problems)

answered Dec 12, 2009 at 9:55
Sign up to request clarification or add additional context in comments.

3 Comments

I upvoted this because it's the correct answer, but only after overcoming my reflexive urge to downvote any post which contains code that re-#defines the for keyword.
I agree. This is the answer to the OP, not the answer to the question "should I actually do this?", to which the answer is an emphatic "no!".
Best to do this in a public header, to increase the fun for others using your library :-) :-) :-)
2

You can use #define directive

#define loopOver for
#define addTo +

But this is just bad!

And no - this is no operator overloading question. Here You have some informations: http://en.wikibooks.org/wiki/C%2B%2B_Programming/Operators/Operator_Overloading

answered Dec 12, 2009 at 9:59

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.