Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between if as an expression and if as a statement

So I was watching this video on the Go language - https://www.youtube.com/watch?v=p9VUCp98ay4 , and at around 6:50 a guy asks a question about why they implemented if's as statements and not expressions. What is the difference between those two implementations? As far as I know, I've never had to change the way I use a conditional based on the language.

Edit: and what does he mean that "you need values rather than variables" in his question?

like image 576
Mauricio Avatar asked Jun 27 '17 01:06

Mauricio


People also ask

What is an expression vs statement?

statements. In programming language terminology, an “expression” is a combination of values and functions that are combined and interpreted by the compiler to create a new value, as opposed to a “statement” which is just a standalone unit of execution and doesn't return anything.

What is difference between expression and statement with example?

An expression is something that can be reduced to a value, for example "1+3" is an expression, but "foo = 1+3" is not. If it doesn't work, it's a statement, if it does, it's an expression. as it cannot be reduced to a value.

What is if as statement?

The IF statement is a decision-making statement that guides a program to make decisions based on specified criteria. The IF statement executes one set of code if a specified condition is met (TRUE) or another set of code evaluates to FALSE.

What is the difference between IF ELSE statement and if else if statement?

The difference between else and else if is that else doesn't need a condition as it is the default for everything where as else if is still an if so it needs a condition.


1 Answers

The difference between expressions and statements is that expressions produce a value and thus can be used in places where values are required. So expressions can be used as values for variables, arguments to functions or operands to operators. Statements can't.

and what does he mean that "you need values rather than variables" in his question?

I assume that by vals he means constants (which are called vals in Scala for example).

If if were an expression, you could do this:

const myValue = if condition { value1 } else { value2 }

Since if is not an expression, you have to do this:

var myValue
if condition {
    myValue = value1
} else {
    myValue = value2
}

So you needed to make your variable mutable (use var instead of const), which is what the person asking the question likely meant.

like image 64
sepp2k Avatar answered Oct 01 '22 20:10

sepp2k