7 years, 2 months ago.

Hi can anyone help me with proper syntax of function call by reference in mbed compiler.

void swap(int *x, int *y);

int main () { int a = 100; int b = 200;

swap(&a, &b); } void swap(int *x, int *y) { int temp; temp = *x;

  • x = *y;
  • y = temp; }

1 Answer

7 years, 2 months ago.

Hello Numair,

You can apply the syntax as below:

#include "mbed.h"

void swap(int& x, int& y);

int main(void) {
    int a = 100;
    int b = 200;

    printf("a = %d\r\n", a);
    printf("b = %d\r\n", b);

    printf("Calling swap by reference.\r\n");
    swap(a, b);

    printf("a = %d\r\n", a);
    printf("b = %d\r\n", b);
}

void swap(int& x, int& y) {
    int temp;
    temp = x;
    x = y;
    y = temp;
}

See https://www.tutorialspoint.com/cplusplus/cpp_function_call_by_reference.htm for more details.

However, there are situations in MBED when one should consider to pass pointers rather then references when designing functions as explained by Mark.

Accepted Answer