Can I assign value within a parameter?

Asked

Viewed 63 times

1

I have a work in pseudocode, where I needed to create a function to receive a user value and do the mod by 2, so I did so:

Função Módulo (x,b=2: inteiro) : inteiro

Var
   i:inteiro
Inicio
 Escreva("Digite um número:")
 Leia (x)
 i=x mod b
 Escreva("O módulo de "+x+" é "+i)
Fim_função"

I can add the value 2 to the variable b within the parameter?

  • Yes, this will leave the variable with a default value if you call this function and do not enter the second parameter, it will use the set value as default.

1 answer

0

Depending on the language, as it is pseudo-code, it will depend on your teacher whether to accept or not.

This is called "predefined parameter" (or anything that has the same meaning).

In general, the resource works by assigning the value defined in the method signature if there is no argument corresponding to that parameter.

The fact is that many languages accept this and some (like Javascript) have adapted to make it work.

A very simple example in JS.

function modulo(x, mod = 2) {
  return x % mod;
}

console.log(modulo(5));    // Aqui, vai fazer mod 2, pq não tem segundo argumento
console.log(modulo(8, 3)); // Aqui, vai fazer mod 3

Browser other questions tagged

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