c program

Status
Not open for further replies.

saro_gn

Broken In
hi
i write the following program.
--------------------------------------------------------------
# define swap(a,b) temp=a; a=b; b=temp;
main( )
{
int i, j, temp;
i=5;
j=10;
temp=0;
if( i > j)
swap( i, j );
printf( "%d %d %d", i, j, temp);
}
-----------------------------------------------------
i got ans 10 0 0
i could't understand the concept.
pls any one help me.

bye.,
saravana.
 

sakumar79

Technomancer
I dont think it is valid to put more than one statement in a #define (you have 3 - temp=a, a=b and b=temp). Am I wrong? Try putting the swap in a function and access the parameters a and b by reference...

Also, since 5 is less than 10, you should not even be looking at the swap function right?

I will try and look into it tonight and get back to you...

Arun
 

aadipa

Padawan
saro_gn said:
hi
i write the following program.
--------------------------------------------------------------
# define swap(a,b) temp=a; a=b; b=temp;
main( )
{
int i, j, temp;
i=5;
j=10;
temp=0;
if( i > j)
swap( i, j );
printf( "%d %d %d", i, j, temp);
}

Just a small change needed
Code:
#define swap(a,b) {temp=a; a=b; b=temp;}

note that i have put a block statement.

Earlier in your code, temp=a; is only statement that was depending on if() condition. This is due to the fact that preprocessor replaces #define with its code before compiling.
 

sakumar79

Technomancer
aadipa's correction worked (checked with dev c++)

and i understand now why you get the strange 10 0 0 output (aadipa said it in the last paragraph but i figured you might like a more detailed explanation).

as aadipa said in his last paragraph, the preprocessor replaces #define with its code before compiling... so, the code becomes

int main()
{
int i, j, temp;
i=5;
j=10;
temp=0;
if( i > j)
temp=i;
i=j;
j=temp;
cout<<i<<" "<<j<<" "<<temp;
system("PAUSE");
return 0;
}

so, temp=i is not executed since i is less than j, but i=j and j=temp are executed...

Arun
 
Status
Not open for further replies.
Top Bottom