Noobish question

I used to know this but I haven't coded for a bit (no pun intended). How do you make an alias for a command? Like so when you put in cout << myAlias; it prints... lets say... Hello World. It was not a function. I can't remember and its driving me nuts.
Are you talking about #define?

1
2
3
4
#define something "Hello World!"
//...
    std::cout << something;
//... 
Thank you! I was searching everywhere for an Alias keyword.... I feel dumb now.

Edit: could you define a chunk of code, IE:

1
2
3
4
5
#define battleLoop{

... something here

}


or does it only work for text? I guess you would use a function anyways. Just wondering, I like to know all the ways to solve a problem.
Last edited on
Not a problem.
could you define a chunk of code


Sure you can, just put whatever you want to be part of the definition between backslashes.

Ex.

1
2
#define SORT_VEC() \
	sort( v.begin(), v.end() ); \ 


Then you would just call it by saying

 
SORT_VEC();


Make sure of course you have a vector named v
Last edited on
Is that any better then making a function? Just wondering.
Ack! Don't get caught up in this!

Macros are evil. Refrain from using them. Especially for making large blocks of code.

Functions and const variables are always better to use when possible for many reasons.

per your original problem:

1
2
3
4
5
6
7
// bad:
#define myAlias "Hello World"
cout << myAlias;

// good:
static const char* myAlias = "Hello World";
cout << myAlias;


You can use macros to expand blocks of code as well.. but again you should refrain from doing this:

1
2
3
4
5
6
// bad:
#define SORT_VEC(v)   sort( v.begin(), v.end() )

// good:
template<typename T>
inline void SORT_VEC(T& v) { sort( v.begin(), v.end() ); }



Macros are bad because:

1) They ignore scope rules (pollute namespace)
2) They expand code that might be better left unexpanded (inlining stuff that shouldn't be inlined)
3) They can lead to unexpected errors (both compiletime and runtime) if you're not very very careful
4) They ignore C++ rules because they're processed before the C++ compiler starts
5) They are not recognizable symbols in the debugger
6) You can't get a pointer to a constant defined by #define if you need it
7) other reasons

Sometimes they are the best option -- but not in any of the instances mentioned in this thread. Refrain from using them whenever possible.
Last edited on
Ok. I was not planning on using them, I just wanted to know HOW to use them.
Topic archived. No new replies allowed.