macro function
Hi all,
look at this function...
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
#include <string>
#include <iostream>
string TEST1(string str){
str.append("my string");
return str;
}
int main(){
string stri;
stri = TEST1("this string is "); cout << stri<<endl;
} // output -- this string is my string
|
Now, how can i implement this function as macro and how will be returned..
please can you explain it through executable example
thanks for each support
I would suggest use inline functions instead.
1 2 3 4 5
|
inline string TEST1(string str) {
return str.append("my string");
}
|
Acually, i know that i can use the inline function.. but i am interessted to know how the returned functions could be implemented as macro..
could anybody explain me that?
thanks alot
A
macro is just a text-replacement.
Given the source code:
1 2 3
|
#define PI 3.141592
cout << PI << endl;
|
The C preprocessor replaces every instance of "PI" with the text "3.141592". The compiler then sees the source code as:
1 2 3
|
cout << 3.141592 << endl;
|
Macro functions work the same way. To make your macro function, work in reverse.
1 2 3 4
|
string str = "this string is ";
string stri;
stri = str.append( "my string" );
cout << stri << endl;
|
becomes
1 2 3 4 5 6
|
#define TEST1( s ) s.append( "my string" )
string str = "this string is ";
string stri;
stri = TEST1( str );
cout << stri << endl;
|
There is an important thing about macro arguments -- they are simple
text substitutions. You cannot treat them like you did above.
There is, however, a simple macro trick to concatenate strings.
1 2 3 4 5 6 7 8 9 10
|
#include <iostream>
using namespace std;
#define CATS( s ) s "my string"
int main()
{
cout << CATS( "this string is " ) << endl;
return 0;
}
|
which becomes:
1 2 3 4 5 6 7 8 9 10
|
#include <iostream>
using namespace std;
int main()
{
cout << "this string is " "my string" << endl;
return 0;
}
|
Hope this helps.
Last edited on
Topic archived. No new replies allowed.