Q:

Rust program to demonstrate the call by reference parameter passing

belongs to collection: Rust Functions Programs

0

In this program, we will create a user-defined function Swap() to swap numbers using call-by-reference parameter passing.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

The source code to demonstrate the call by reference parameter passing is given below. The given program is compiled and executed successfully.

// Rust program to demonstrate the 
// call by reference parameter passing

fn Swap(num1:&mut i32, num2:&mut i32) {
    let mut temp:i32 = 0;
    
    temp = *num1;
    *num1 = *num2;
    *num2 = temp;
}

fn main() {
    let mut num1:i32 = 10;
    let mut num2:i32 = 20;
    
    println!("Numbers before swapping: \nnum1:{0}\nnum2:{1}", num1, num2);
    Swap(&mut num1, &mut num2);
    println!("Numbers after swapping: \nnum1:{0}\nnum2:{1}", num1, num2);
}

Output:

Numbers before swapping: 
num1:10
num2:20
Numbers after swapping: 
num1:20
num2:10

Explanation:

In the above program, we created two functions Swap() and main(). The Swap() function is a user-defined function that accepts two parameters using call by reference mechanism and exchanges the value of variables and returned the updated value to the calling function.

In the main() function, we created two integer variables num1num2 which were initialized with 10, 20 respectively. Then we called the Swap() function with arguments num1 and num2 and printed the result.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Rust program to pass an array in a function... >>
<< Rust program to demonstrate the call by value para...