What is the C++ clamp value?

Imagine you are a programmer and want to make a program where a number input should always be within a specified range. It is very difficult to notify or even remember the ranges after the program is made. Therefore, the C++ Clamp is used.

Scenario

You want to build a program so whenever a user enters a number, you make sure it is changed to fall into a specific range of [10-20]. For a number greater than 20, it should be clamped to 20. For a number less than 10, it should be clamped to 10. For numbers within the range, no modifications are made.

1 of 3

Code

#include <iostream>
// important to include algorithm library
#include <algorithm>
using namespace std;
// Range [10 - 20]
int low = 10, high = 20;
int main()
{
// Array of 5 having elements to be clamped
int arr[5] = { 8, 12, 20, 25, 5};
// Printing the array after clamped
cout<<"Numbers before Clamp: ";
for (int i = 0; i < 5; i++)
cout << arr[i] << " ";
cout<<endl;
// clamp the elements at every index of array
for (int i = 0; i < 5; i++) {
arr[i] = std::clamp(arr[i], low, high);
}
// Printing the array after clamped
cout<<"Numbers After Clamp: ";
for (int i = 0; i < 5; i++)
cout << arr[i] << " ";
cout<<endl;
}
Numbers before Clamp: 8 12 20 25 5
Numbers after Clamp: 10 12 20 20 10

In the code above, we can see how 8 and 5 were clamped to 10 since they are less than 10. Number 25 was clamped to 20 since it is greater than 20. Numbers 12 and 20 were within range, so no modifications were made.

In real-life scenarios, clamps ensure that the list of inputs is specified to a given range. Moreover, it prevents size overflow.

Copyright ©2024 Educative, Inc. All rights reserved