When should I or should I not use the if without keys?

Asked

Viewed 2,860 times

4

I usually use always with keys because until today I do not know how exactly is the function of if without keys and if Else can also be without keys. Is there any variation in behavior between javascript and C#? and other languages?

Some examples that would confuse me whether or not they work:

Example 1:

if(true)
    variavel = 55;
else
    variavel = 100;

Example 2:

if(true)
    variavel1 = 55;
    variavel2 = 40;
else
    variavel1 = 100;
    variavel2 = 150;

Example 3

if (true)
   variavel1 = 55;
else{
   variavel1 = 100;
   variavel2 = 200;
}
  • Simply when the instruction you need to validate is done on a single line, after the first line what comes will not be within your if or Else. the ideal is always to use.

  • All these examples work (compile), may not do what you want. So always use keys.

1 answer

7


The IF without keys causes only the next expression to be evaluated.

In a variation of your example 2,

if(variavel == true)
    variavel1 = 55;  //Será executado apenas se variavel == true;
    variavel2 = 40;  // Será executado incondicionalmente.

Incidentally, a better way to view the above code would be:

if(variavel == true)
    variavel1 = 55;

variavel2 = 40; 

Realize that expression is different from line. The sequence below will behave exactly in the same way as in example 2:

if(variavel == true)
    variavel1 = 55; variavel2 = 40;
//                     ^- Execução incondicional
//     ^- Execução condicional
  • The explanation of the expression != line was essential to my understanding! I only continue with the doubt in relation to the Lse in these same cases.

Browser other questions tagged

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