LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   question on #define (https://www.linuxquestions.org/questions/programming-9/question-on-define-122342/)

h/w 12-03-2003 12:49 PM

question on #define
 
can we do a #define at any point in the code?

say i perform some task, and get a result xyz.

can i do a '#define RESULT xyx" at some point in the code?

thanks.

MartinN 12-03-2003 12:58 PM

A define is expanded by the C pre-processor. What it does is that it replaces, textually, the first argument of the define with the second before passing the code on to the compiler.

Because of that, your question doesn't make sense! If the "answer" is not known at compile time, then (obviously) the pre-processor can't make the replacing.

Regards
Martin

h/w 12-03-2003 01:06 PM

right! thanks! :)

jim mcnamara 12-03-2003 02:04 PM

#define will expand macros which can do things:
Code:

#define zout(z) memset(&z,0x00,sizeof(z))

.........
zout(mystring);
will expand to:
memset(&mystring,0x00,sizeof(mystring));

You also #define multiline macros which are really more like a way to inline a function:

Code:

// this function does a complex square calc
#define CMPLXsqr_old(out)        \   
  (out).y = (old.x+old.x) * old.y;\ 
  (out).x = tempsqrx - tempsqry


MartinN 12-03-2003 03:12 PM

Now I must raise a finger of warning:tisk:about the use of pre-processor macros.

Look at this seemingly innocent macro:
Code:

#define MAX(x, y)  ((x)>(y)?(x): (y))
Now consider what happens if we call this with
Code:

MAX(++j, ++k);
That looks pretty straight forward and correct, right? Wrong! Well what happens is that whichever variable is bigger gets increased twice! Why? Because the macro has been textually expanded to
Code:

++j > ++k ? ++j : ++k;
This is why inline is a good keyword in C++.

Regards
Martin

h/w 12-03-2003 04:40 PM

right. thanks. :)

jim mcnamara 12-03-2003 04:42 PM

But is not available for a lot of plain C implementations.

h/w 12-03-2003 05:14 PM

u mean, inline isnt ?


All times are GMT -5. The time now is 11:38 AM.