Can anyone explain to me what this code does line by line?

Asked

Viewed 51 times

1

void primeiro(int a) {
  a *= 2;
  printf("%d", a);
}

void segundo(int *u) {
 int x = 1;
  x = x + *u;
  primeiro(x);
  *u = x++;
}
int main() {
  int x = 5;
  segundo(&x);
  printf(":%d\n", x);
}

2 answers

2

The code starts by defining the variable x as whole with the value 5 and calls the function segundo with the memory address of the variable x:

int main() { 
    int x = 5;
    segundo(&x);

In this capacity segundo another variable is created x with the value 1:

void segundo(int *u) {
    int x = 1;

To this variable is added the value pointed by the pointer u. This pointer was what was passed on main and therefore points to the x of main, that has the value 5:

x = x + *u;

Will thus keep 6 in the variable x of function segundo. Now it’s called the function primeiro passing this variable x:

primeiro(x);

In function primeiro multiply the value received by 2, that will be 6*2 and show with printf:

void primeiro(int a) {
    a *= 2;
    printf("%d", a);
}

This variable a is a copy of x passed from the previous function, so multiplication does not change this value.

Once this function is over we take over the function segundo after the instruction primeiro(x); which has already been executed, leaving only to do the instruction:

*u = x++;

Indicating that the value pointed by u becomes x (that it was already) and that x after this instruction increases. But this x is a local variable and so this post increment has no real effect since there are no more instructions in this function.

After the two functions have been carried out, the printf in the main with the value of x that will be 6:

int main() {
    ...
    printf(":%d\n", x);

To output on the console of all program execution is:

12:6

0

void primeiro(int a) { // Função sem retorno, com parâmetro do tipo inteiro.
  a *= 2; // a recebe um valor inteiro e multiplica por 2.
  printf("%d", a); // Exibe o resultado na tela, formatado como decimal "%d".
}

void segundo(int *u) { // Função sem retorno, com ponteiro como parâmetro.
 int x = 1; // Variável x recebe o valor inteiro 1.
  x = x + *u; // x recebe o valor de x + o valor do ponteiro, passado por referência.
  primeiro(x); // Chama a função primeiro() e passa o resultado de x.
  *u = x++; // O ponteiro recebe um incremento inteiro. O valor atual + 1.
}
int main() { // Função principal
  int x = 5; // Variável x recebe o valor inteiro 5.
  segundo(&x); // Passa o valor da variável x para a função segundo() por referência.
  printf(":%d\n", x); // Exibe o valor da variável x com as alterações feitas pela função segundo().
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.