Skip to content
Exercise · Pointers · lesson 7 of 8

Exercise: swap

Write a function func swap(a, b *int) that swaps the values of the variables a and b point to. Then write a function func sortPair(a, b *int): after it, the smaller of the two values is in *a and the larger one is in *b.

  • x, y := 1, 2, then swap(&x, &y) → x is 2, y is 1
  • x, y := -3, 7, then swap(&x, &y) → x is 7, y is -3
  • x, y := 5, 2, then sortPair(&x, &y) → x is 2, y is 5

Constraints: the pointers are not nil; a and b may point to the same variable, and then its value does not change; sortPair leaves an ordered pair as it is.

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

swap.go — go
go · 8 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