Practical C Programs
Retry Budget
A retry loop should stop when it succeeds or when the attempt budget is exhausted.
attempt budget
The maximum attempt count bounds the loop even when the operation does not succeed.
success condition
The loop checks success after each attempt and exits early when possible.
Retry Budget
retry_budget.c
Replay: real traced execution (multi-file project)
#include <stdio.h>
int main(void) {
int successAt = 2;
int maxAttempts = 3;
int attempts = 0;
int ok = 0;
while (attempts < maxAttempts && ok == 0) {
attempts++;
if (attempts >= successAt) {
ok = 1;
}
}
printf("successAt=%d attempts=%d ok=%d\n", successAt, attempts, ok);
return 0;
}
#include <stdio.h>
int main(void) {
int successAt = 1;
int maxAttempts = 3;
int attempts = 0;
int ok = 0;
while (attempts < maxAttempts && ok == 0) {
attempts++;
if (attempts >= successAt) {
ok = 1;
}
}
printf("successAt=%d attempts=%d ok=%d\n", successAt, attempts, ok);
return 0;
}
#include <stdio.h>
int main(void) {
int successAt = 4;
int maxAttempts = 3;
int attempts = 0;
int ok = 0;
while (attempts < maxAttempts && ok == 0) {
attempts++;
if (attempts >= successAt) {
ok = 1;
}
}
printf("successAt=%d attempts=%d ok=%d\n", successAt, attempts, ok);
return 0;
}
successAt ← 2, maxAttempts ← 3, attempts ← 0, ok ← 0
3int main(void) {4 int successAt→ 2 = 2; //@successAt=1, 45 int maxAttempts→ 3 = 3;6 int attempts→ 0 = 0;7 int ok→ 0 = 0;attempts ← 1
pass 1 of 29while (attempts0 < maxAttempts3 && ok0 == 0) {10 attempts→ 1++;11 if (attempts >= successAt) {attempts ← 2
pass 2 of 29while (attempts1 < maxAttempts3 && ok0 == 0) {10 attempts→ 2++;11 if (attempts >= successAt) {ok ← 1
10attempts++;11if (attempts2 >= successAt2) {12 ok→ 1 = 1;13}printf("successAt=%d attempts=%d ok=%d ", successAt, attempts, ok);
16 printf("successAt=%d attempts=%d ok=%d\n", successAt2, attempts2, ok1);17 return 0;18}outputsuccessAt=2 attempts=2 ok=1
successAt ← 1, maxAttempts ← 3, attempts ← 0, ok ← 0
3int main(void) {4 int successAt→ 1 = 1;5 int maxAttempts→ 3 = 3;6 int attempts→ 0 = 0;7 int ok→ 0 = 0;attempts ← 1
9while (attempts0 < maxAttempts3 && ok0 == 0) {10 attempts→ 1++;11 if (attempts >= successAt) {ok ← 1
10attempts++;11if (attempts1 >= successAt1) {12 ok→ 1 = 1;13}printf("successAt=%d attempts=%d ok=%d ", successAt, attempts, ok);
16 printf("successAt=%d attempts=%d ok=%d\n", successAt1, attempts1, ok1);17 return 0;18}outputsuccessAt=1 attempts=1 ok=1
successAt ← 4, maxAttempts ← 3, attempts ← 0, ok ← 0
3int main(void) {4 int successAt→ 4 = 4;5 int maxAttempts→ 3 = 3;6 int attempts→ 0 = 0;7 int ok→ 0 = 0;attempts ← 1
pass 1 of 39while (attempts0 < maxAttempts3 && ok0 == 0) {10 attempts→ 1++;11 if (attempts >= successAt) {All 3 passes — pass 1 is the card above pass attempts1 0 → 1 2 1 → 2 3 2 → 3 printf("successAt=%d attempts=%d ok=%d ", successAt, attempts, ok);
16 printf("successAt=%d attempts=%d ok=%d\n", successAt4, attempts3, ok0);17 return 0;18}outputsuccessAt=4 attempts=3 ok=0