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?
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.
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.
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.
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.
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 val
s 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With