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

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);
}
    
asked by anonymous 14.01.2018 / 17:41

2 answers

2

The code begins by setting the variable x to integer 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 function segundo is created another variable x with value 1 :

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

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

x = x + *u;

This will save 6 to the x variable of the segundo function. Now we call the primeiro function by passing this variable x :

primeiro(x);

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

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

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

Once this function is finished, we return to the segundo function following the primeiro(x); statement that has already been executed,

*u = x++;

That indicates that the value pointed to by u becomes x (which was already) and that x after this statement 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 are executed, the printf in main is written with the value of x that will be 6 :

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

The console exit of all program execution is:

12:6
    
14.01.2018 / 18:03
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().
}
    
14.01.2018 / 18:07