Clamp Integer Function
Clamps an integer value to a specified range.
Description
A utility function to constrain an integer value within a specified range. If the value is less than the minimum, it returns the minimum. If the value is greater than the maximum, it returns the maximum. Otherwise, it returns the value itself.
Code
#ifndef CLAMP_H#define CLAMP_H/** * Clamps an integer value to a specified range. * * @param value The integer value to clamp. * @param min The minimum value of the range. * @param max The maximum value of the range. * @return The clamped value. */int clamp(int value, int min, int max);#endif /* CLAMP_H */
#include "clamp.h"int clamp(int value, int min, int max) { if (value < min) { return min; } else if (value > max) { return max; } else { return value; }}
#include <stdio.h>#include "clamp.h"int main() { int value = 10; int min = 0; int max = 5; int clamped_value = clamp(value, min, max); printf("Original value: %d\n", value); printf("Clamped value: %d\n", clamped_value); return 0;}
Comments
No comments yet. Be the first to comment!
Please login to leave a comment.