# 16. If Else

### If Statement

If like in most other programming languages, is used to control flow of execution based on condition. Common semantic for if statement is&#x20;

`if condition { code to execute}`

{% code title="main.go" %}

```go
flag := true

if flag {
	fmt.Println("Flag is present")
}
```

{% endcode %}

### Stronger Semantics

If statement in Go has stronger semantics than some other programming languages. We can not provide integer or string as condition for if statement.Condition has to be a Boolean value in if statement. Following code will not compile.

{% code title="main.go" %}

```go
count := 1
if "hello" {
	fmt.Println("Invalid if")
}
if count {
	fmt.Println("Invalid if")
}
```

{% endcode %}

Also, when code to execute is single statement, some programming languages allow to skip curly braces, but not in Go. As with other code blocks, curly braces need to start from same line.

### Multiple Branches

To work with multiple branches, Go provide `if...else` form

{% code title="main.go" %}

```go
marks := 70
if marks > 80 {
	fmt.Println("Great!")
} else if marks > 60 {
	fmt.Println("Good!")
} else if marks > 40 {
	fmt.Println("You can do better!")
}
```

{% endcode %}

Remember that once a if condition is satisfied, it will not check for remaining conditions in other else blocks.

### Ternary Operator

Go does not have ternary operator. This has been well addressed in Go FAQ.

> &#x20;The reason `?:` is absent from Go is that the language's designers had seen the operation used too often to create impenetrably complex expressions. The `if-else` form, although longer, is unquestionably clearer. A language needs only one conditional control flow construct. - <https://golang.org/doc/faq#Does_Go_have_a_ternary_form>

### GitHub Code

{% embed url="<https://github.com/gophersumit/codewithgo-samples/tree/master/if>" %}
