446,341 Members | 1,396 Online Need help? Post your question and get tips & solutions from a community of 446,341 IT Pros & Developers. It's quick & easy.

# Introduction to C language

 P: n/a void swap(int *p,*q) { int t; t=*p; *p=*q; *q=t; } coresponding call statement x=4; y=5; swap(&x,&y); this function does swaping but if we write this swap function in call by value then swapping is not done why? Sep 22 '07 #1
5 Replies

 P: n/a void swap(int *p,*q) { int t; t=*p; *p=*q; *q=t; } This function will take the values of p and q as addresses of the values to be swapped. And these addresses in the memory space is a 2 byte integer. coresponding call statement x=4; y=5; swap(&x,&y); this function does swaping but if we write this swap function in call by value then swapping is not done why? That is why this statement will not given an error; on the other hand, it will locate address locations 4 and 5 and see the addresses corresponding to the contents in their cell would have swapped values. Sep 22 '07 #2

 P: n/a On Sat, 22 Sep 2007 19:11:13 -0000, Vivek

 P: n/a piyush San Diego Supercomputer Center <* "We must do something. This is something. Therefore, we must do this." -- Antony Jay and Jonathan Lynn, "Yes Minister" Sep 22 '07 #4

 P: n/a Vivek void swap(int *p,*q){int t;t=*p;*p=*q;*q=t;} This function will take the values of p and q as addresses of the values to be swapped. And these addresses in the memory space is a 2 byte integer. The size of an object of type 'int' is 'sizeof(int)'. It may be two bytes on some systems, but I've seen 4 and even 8 bytes. The size of an address also varies from one system to another, and addresses are *not* integers. >coresponding call statementx=4;y=5;swap(&x,&y); >this function does swaping butif we write this swap function in call by value then swapping is notdone why? That is why this statement will not given an error; on the other hand, it will locate address locations 4 and 5 and see the addresses corresponding to the contents in their cell would have swapped values. Um, no, nothing in the code above refers to memory addresses 4 and 5. x and y are objects of type int whose *values* are 4 and 5. We have no idea where in memory those objects are stored, but the program can find out by referring to '&x' and '&y'. If the swap() function, which takes two pointer arguments, were called as 'swap(x, y)' or 'swap(4, 5)', it would be an error; you can't pass an integer value to something that expects a pointer. (There's one exception to this, involving null pointers). I suggest you take a look at the comp.lang.c FAQ, . -- Keith Thompson (The_Other_Keith) ks***@mib.org San Diego Supercomputer Center <* "We must do something. This is something. Therefore, we must do this." -- Antony Jay and Jonathan Lynn, "Yes Minister" Sep 22 '07 #5

 P: n/a On 9 23 , 12 02 , piyush

### This discussion thread is closed

Replies have been disabled for this discussion. 