I'm going to use the swap function. (It's a simple code, so please answer.)

Asked 2 years ago, Updated 2 years ago, 66 views

void swap(int *x, int *y) { int temp; temp = *x; *x = *y; *y = temp; return *x, *y; } int main() { int a=10, b=20; swap(a, b); printf("a: %d, b: %d", a, b); } If I run this, there will be an error. Why is that?

swap

2022-09-22 14:23

1 Answers

#include <stdio.h>

void swap(int *x, int *y)
{
    int temp;
    temp = *x; 
    *x = *y;
    *y = temp;
    return *x, *y;
}
int main()
{
    int a=10, b=20;
    swap(a, b);
    printf("a: %d, b: %d", a, b);
}

I'm at a loss where to begin.

First, in mathematics, a function has one Y value returned to the input X value.

If two are returned, it is not a function.

Sometimes, in a language like Python, it seems like two or more are returned, but it's one triple.

If you want to return more than two values because there is no such thing as a tutelage, you must return one value (structure) using a structure.

or

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

From

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

It has to be something like that.

And for the main function, the pointer must be substituted as shown below.

int main()
{
    int a=10, b=20;
    The swap(&a, &b); // swap function must substitute a pointer.
    printf("a: %d, b: %d", a, b);
}

In summary, it should be as below.

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

int main()
{
    int a=10, b=20;
    The swap(&a, &b); // swap function must substitute a pointer.
    printf("a: %d, b: %d", a, b);
}


2022-09-22 14:23

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.