0

I've got a simple program to swap 2 variables.

#include <stdlib.h>
#include <stdio.h>
int einlesen (void);
int tausch(int,int);
void ausgabe(int,int);
int a,b,tmp;
int main()
{
  printf("Bitte geben Sie 2 Zahlen zum Tauschen ein!");
  einlesen();
  tausch(a,b);
  ausgabe(a,b);
}
int einlesen (void)
{
  scanf("%i%i",&a,&b);
}
  int tausch(int x,int y) !!!!
{
  tmp=a;
  a=b;
  b=tmp;
}
void ausgabe(int a,int b)
{
  printf("%i%i",a,b);
}

It works, but my question is why the below doesn't work?

int tausch(int a,int b)
Lundin
  • 195,001
  • 40
  • 254
  • 396
Marius
  • 51
  • 1
  • 6
  • 1
    Because it's swapping `a` and `b` instead of `x` and `y`. You're also passing the arguments by value instead of reference or pointer so even if you swap the values it won't stick. I suggest you use `std::swap` instead. – Captain Obvlious Jun 19 '14 at 07:34
  • because *you* swap (a) and (b) inside the function. change the code inside the function accordingly. – Tigran Jun 19 '14 at 07:35
  • You originally tagged this as C++, C and C#. Which one of those languages are you asking about? – juanchopanza Jun 19 '14 at 07:38
  • It's right, but `a` and `b` are global. It seems like `int tausch(void)` :). – someuser Jun 19 '14 at 07:39

0 Answers0