0
0
Cprogramming~10 mins

Defensive programming practices - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Defensive programming practices
Start Program
Input Data
Check Input Validity?
NoHandle Error
Yes
Process Data Safely
Check for Errors During Processing?
YesHandle Error
No
Output Result
End Program
The program starts by getting input, checks if input is valid, handles errors if needed, processes data safely, checks for errors again, then outputs the result and ends.
Execution Sample
C
#include <stdio.h>
#include <stdlib.h>

int main() {
    int num;
    if (scanf("%d", &num) != 1) {
        printf("Invalid input\n");
        return 1;
    }
    if (num <= 0) {
        printf("Number must be positive\n");
        return 1;
    }
    printf("You entered: %d\n", num);
    return 0;
}
This code reads an integer, checks if input is valid and positive, handles errors by printing messages, then prints the number.
Execution Table
StepActionInput/ConditionResultNext Step
1Read input with scanfUser enters 'abc'scanf returns 0 (failure)Print 'Invalid input' and exit
2Print error messageInvalid input detectedOutput: 'Invalid input'Program ends with return 1
3Program endsExit code 1No further actionEnd
4Read input with scanfUser enters '5'scanf returns 1 (success), num=5Check if num <= 0
5Check if num <= 0num=5FalsePrint 'You entered: 5'
6Print valid inputnum=5Output: 'You entered: 5'Program ends with return 0
7Program endsExit code 0No further actionEnd
💡 Program stops when input is invalid or after printing the valid number.
Variable Tracker
VariableStartAfter Step 1After Step 4After Step 5Final
numundefinedundefined (scanf failed)555
Key Moments - 3 Insights
Why do we check the return value of scanf?
Because scanf returns the number of successfully read items. If it is not 1, input was invalid. This is shown in execution_table row 1 where scanf fails and we handle the error.
Why do we check if num <= 0 after reading input?
To ensure the number meets expected conditions (positive). This prevents invalid data from causing problems later. See execution_table row 5 where the condition is checked.
What happens if input is invalid?
The program prints an error message and exits early to avoid further errors. This is shown in execution_table rows 2 and 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'num' after step 4 when input is '5'?
A5
Bundefined
C0
D-1
💡 Hint
Check variable_tracker column 'After Step 4' for 'num'
At which step does the program detect invalid input and stop?
AStep 2
BStep 5
CStep 1
DStep 6
💡 Hint
Look at execution_table row 1 where scanf fails and program decides to stop
If the input was '-3', which step would handle this error?
AStep 1
BStep 5
CStep 4
DStep 6
💡 Hint
Check where the condition 'num <= 0' is evaluated in execution_table
Concept Snapshot
Defensive programming means checking inputs and conditions before using data.
Always verify input success (e.g., scanf return value).
Check data validity (e.g., positive numbers).
Handle errors early by printing messages and exiting.
This prevents crashes and unexpected behavior.
Full Transcript
This example shows defensive programming in C. The program reads an integer from the user. It first checks if the input was successfully read by checking scanf's return value. If input is invalid, it prints an error and stops. If input is valid, it checks if the number is positive. If not, it prints an error and stops. Otherwise, it prints the number and ends normally. This approach avoids problems caused by bad input or unexpected values.