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, thenclamp(&n, 0, 10)→nis10n := -4, thenclamp(&n, 0, 10)→nis0n := 7, thenclamp(&n, 0, 10)→nis7
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.
Subscribe to take the course
The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.