Input Validation Patterns
Range Clamp
Clamping keeps an incoming value inside the range that later code expects.
Range Clamp
range_clamp.c
#include <stdio.h>
int clampScore(int requested) {
int clamped = requested;
if (clamped < 0) {
clamped = 0;
}
if (clamped > 100) {
clamped = 100;
}
return clamped;
}
int main(void) {
int requested = ;
int score = clampScore(requested);
int passing = score >= 60;
printf("requested=%d score=%d passing=%d\n", requested, score, passing);
return 0;
}
#include <stdio.h>
int clampScore(int requested) {
int clamped = requested;
if (clamped < 0) {
clamped = 0;
}
if (clamped > 100) {
clamped = 100;
}
return clamped;
}
int main(void) {
int requested = ;
int score = clampScore(requested);
int passing = score >= 60;
printf("requested=%d score=%d passing=%d\n", requested, score, passing);
return 0;
}
#include <stdio.h>
int clampScore(int requested) {
int clamped = requested;
if (clamped < 0) {
clamped = 0;
}
if (clamped > 100) {
clamped = 100;
}
return clamped;
}
int main(void) {
int requested = ;
int score = clampScore(requested);
int passing = score >= 60;
printf("requested=%d score=%d passing=%d\n", requested, score, passing);
return 0;
}
lower bound
Values below the allowed range are raised to the minimum.
upper bound
Values above the allowed range are lowered to the maximum.