#include<conio.h>
#include<stdio.h>
# define swap(a,b) temp=a; a=b; b=temp;
void main( )
{
int i, j, temp;
clrscr() ;
i=5;
j=10;
temp=0;
if( i > j)
swap( i, j );
printf( "%d %d %d", i, j, temp);
getch() ;
}
why o/p->10 0 0
*Please* read the FAQ before asking more questions here. It's at
<
http://www.eskimo.com/~scs/C-faq/faq.html>. We'd much rather spend
time answering real questions than covering the basics that have
already been covered again and again.
The declaration "void main()" is wrong; the correct declaration is
"int main(void)" (or "int main(int argc, char **argv)" if you want to
use command-line arguments).
The <conio.h> header, and the clrscr() and getch() functions, are
non-standard. There's no need for your program to use them anyway
(though you might need something like the final getch() to keep the
output window open).
The program's output should end in a newline ("\n"); otherwise,
there's no guarantee that the output will show up. (It might happen
to do so on your system, but we're interested in portable code here.)
On to your actual problem: you need to keep in mind that macro
expansion works on text, not on statements or expressions (*). A
macro invocation might look like a function call, but it's not going
to behave like one unless the macro is written very carefully. Your
swap macro isn't.
You have:
if( i > j)
swap( i, j );
(BTW, the second line should be indented.)
The preprocessor expands this to:
if( i > j)
temp=i; i=j; j=temp;
which is equivalent to:
if (i > j)
temp = i;
i = j;
j = temp;
Only the first assignment is controlled by the if statement; the
others are executed unconditionally.
An improved version of your swap macro might be:
#define swap(a,b) \
do { \
int temp; \
temp=(a); (a)=(b); (b)=temp; \
} while(0)
With this definition, you can eliminate the declaration of temp.
If you have any questions about this macro definition that aren't
answered by reading section 10 of the C FAQ, come back and we'll be
glad to help. If you have questions that *are* answered by the FAQ
please answer them by reading the FAQ; don't waste everybody's time by
posting them here.
Changing your declaration
void main()
to
int main(void)
will help to to be taken far more seriously around here.
(*) Actually the preprocessor works on sequences of "proprocessor
tokens", but the effect is practically the same.