Skip to content
Exercise · Pointers · lesson 8 of 8

Exercise: clamp

Write a function func clamp(x *int, lo, hi int) that keeps the value of the variable x points to within the range from lo to hi. A value below lo becomes lo, and a value above hi becomes hi; a value inside the range stays as it is.

  • n := 15, then clamp(&n, 0, 10) → n is 10
  • n := -4, then clamp(&n, 0, 10) → n is 0
  • n := 7, then clamp(&n, 0, 10) → n is 7

Constraints: x is not nil; lo <= hi, and the bounds may be equal; values at the bounds of the range do not change.

Do not add extra imports unless the task says so explicitly.

clamp.go — go
go · 5 lines
Ctrl+Enter run · Esc leave editor

Subscribe to take the course

The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.

Sign in another way