-1

I have written this program to make the value of a in b and the value of b in a.

For this I created temp as a temporary variable and this is my program:

#include <stdio.h>

int changevalue(int a, int b)
{
    int temp;
    temp = a;
    a = b; 
    b = temp;
}

int main()
{
    int a;
    int b;
    a = 10;
    b = 20; 
    printf("the value of a is %d \n and b is %d",a,b);
    changevalue(a,b);
    printf("the value of a is %d \n and b is %d",a,b);
    return 0;
}

But the values of a and b did not change .

Where is the problem?

wadie el
  • 35
  • 4
  • changevalue change the values of its parameters (copied from main's a and b) but returns nothing, and main's variables are untouched. – L. Scott Johnson Oct 09 '20 at 13:02
  • 2
    You have to use pointers. – Guido Flohr Oct 09 '20 at 13:02
  • Read call by value and call by reference to learn more. – Sayed Sohan Oct 09 '20 at 13:04
  • In C language, when you declare a function with `int function(int a, int b)` and invoke it, the values of `a` and `b` inside the function are copies, thus the original values (in `main`) won't change – Hollyol Oct 09 '20 at 13:05
  • @GuidoFlohr I have started programming since a week ! looking for pointers on google gives too much information that i can not start studying successfly, can you suggest a good reference to learn with with basic and simple examples ? – wadie el Oct 09 '20 at 13:12
  • Pointers are described in every book or course for C. Just follow your current course, and they will come, when it's time. – Guido Flohr Oct 09 '20 at 13:38
  • You can also replace your *function* `changevalue` with a *macro*: `#define changevalue(x, y) { x += y; y = x - y; x -= y; }`. The difference is that a macro is like a template. The code `changevalue(a,b)` is expanded by the preprocessor into `{ a += b; b = a - b; a -= b; }`. In fact, that is a simpler and faster solution for your problem. – Guido Flohr Oct 09 '20 at 13:53

1 Answers1

3

You need to use the pointers:

#include <stdio.h>

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

int main()
{
    int a=10;
    int b=20;
    printf("the value of a is %d \n and b is %d",a,b);
    changevalue(&a,&b);
    printf("the value of a is %d \n and b is %d",a,b);
    return 0;
}
TechGeek49
  • 476
  • 1
  • 7
  • 24
Robert
  • 2,711
  • 7
  • 15