So, I am currently learning C and while trying to replicate the code in the manual I was given, I noticed the output is different from what is demonstrated in the manual.
The program is supposed to swap two numbers repeatedly and each time to increment a variable in order to indicate how many swaps have ocurred. However, when I run it, whether it be on visual studio or on online compilers, the counter increments correctly, but the swaps seem to be one swap behind.
Here is the code:
#include <stdio.h>
int Troca(int* x, int* y) {
static int trocas = 0;
*x = *x + *y;
*y = *x - *y;
*x = *x - *y;
return ++trocas;
}
int main() {
int x = 123, y = 321;
printf("Troca %d: x = %d, y = %dn", Troca(&x, &y), x, y);
printf("Troca %d: x = %d, y = %dn", Troca(&x, &y), x, y);
printf("Troca %d: x = %d, y = %dn", Troca(&x, &y), x, y);
}
I ran the code step by step in visual studio debugger and it shows the variables being swapped, but when it types them onto the console, it is as if it is typing before the swap.
I would like to know if I need to run the swap before the printf and then to assign the swap number to a new variable or if there is anything I am doing wrong here.
Thanks in advance
mgmgmgmg1231 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.