Swap function global variable is not possible

Asked 2 weeks ago, Updated 2 weeks ago, 1 views

int a,b;

void swap(int a, int b);

int main() {

scanf("%d %d",&a,&b);

if(a>b) swap(a,b);
printf("%d %d", a,b);
for(int i=a;i<=b;i++)
    printf("%d ",i);}

void swap(int a, int b){ int temp; temp=a; a=b; b=temp; }

I understand that you have to use a pointer because you have to use the call by reference method for swapping. Instead, if you use a global variable, the contents of the value are stored in memory anyway, so shouldn't it be swapped correctly?

swap global-variable

2022-09-20 15:56

1 Answers

If you write a parameter of a function in the form of a general variable, by default, a value-based transfer occurs.

Since the swap function you just created is in the form of a general variable, such as void swap(intx, inty), if it is actually used in the form of swap(a,b) in the main function, the local variable of the swap function, x, carries a value of a. Regardless of whether a is a local variable or a global variable, the value of a is initialized to the variable x.

Swap functions can be created with void swap(int*px, int*py) using pointers in C language, and swap functions such as void swap(int&x, int&y) in C++ language, including C-un's method.

2022-09-20 15:56

If you have any answers or tips

© 2022 pinfo. All rights reserved.