macro

hello guys i have on question about macro ! ok i want write one macro which it can calculate some thing like :
1
2
3
4
5
6
7
8
int cal(vector<int> &v)
{
int c = 0;
for (unsinged int i = 0; i < v.size(); i++)
c += v[i];

return c;
}


i want write macro of this but how ?

#define cal(x) (.......)

and how can i return value in macro ? if it can !!
A macro is a snippet of code that will be pasted wherever you write "cal". A macro seems to return something when what it pastes is a single expression. You can't do it in this case, and even if you did, why would you? If you want to loose the overhead of calling the function, make it inline.
just like do it :D

i can write something like

#define cal(v, c) (c = 0, for(int i = 0; i < v.size(); i++) c += v[i])
and work but i dont know i have some problem with macro do you know a beast and complete reference about macro in c++?
A possibility is
1
2
3
4
5
6
#define cal(dst,v) {                              \
    int cal_temp=0;                               \
    for (size_t cal_i=0;cal_i<(v).size();cal_i++) \
        cal_temp+=(v)[cal_i];                     \
    (dst)=cal_temp;                               \
} 
Last edited on
tnx yes works. do you have a tutorial or reference (complete) about macro?
Any book on C or C++ covers the preprocessor thoroughly.
i saw , but not completed !
Topic archived. No new replies allowed.