Question

Can a C function modify the value of its input arguments in the calling function. Explain...

Can a C function modify the value of its input arguments in the calling function. Explain your answer and write a small program to demonstrate that it is correct?

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Yes. A 'C' function can modify the value of its input arguments when the arguments are passed to the function by 'call by reference' method, where, address of the argument is copied to the formal parameter. That is, argument pointers are passed to the function.

Since the address of the actual parameters is passed, values of these parameters will be modified on modifying the formal parameters. (formal parameters - pointing to the same address as the actual parameters).

Following code is an example of passing arguments by reference to a function. Here, address of actual arguments a and b are passed by reference to the swap function. Modifying the formal parameters (num1 and num2) in swap function gets reflected in the calling function as well. We can see that the values of a and b are swapped as well.

#include <stdio.h>

//swap the values of 2 variables - also reflected in the calling function variables

//passing arguments by reference
void swap(int *num1, int *num2) {

int temp;
temp = *num1; //the value at num1 is saved in temp
*num1 = *num2; //num2 value to num1
*num2 = temp; //copy temp value to num2
return;
}

int main () {


int a = 10;
int b = 20;

printf("Before swap, value of a : %d\n", a );
printf("Before swap, value of b : %d\n", b );

//&a - address of variable a (or pointer to a)
//&b - address of variable b (or pointer to b)

swap(&a, &b);

printf("value of a after swapping : %d\n", a );
printf("value of b after swapping : %d\n", b );

return 0;
}

Output

: Before swap, value of a 10 Before swap, value of b: 20 value of a after swapping : 20 value of b after swapping : 10

Add a comment
Know the answer?
Add Answer to:
Can a C function modify the value of its input arguments in the calling function. Explain...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT