Argument validation
- C course
- Intermediate
- Lesson 91/116
- 5 min
Learn to validate command-line arguments.
Checking argument count
A program usually expects at least one argument at run time. By checking argc you catch missing input early and show the user a meaningful message.
Example: if (argc < 2) { printf("Error: missing argument\n"); return 1; }. Here argc < 2 is true when only the program name is present (no user argument). Print the error and exit with return 1 so the rest of the code never runs. This is the most common validation pattern in CLI tools and guides users toward correct usage.
Usage message
On error, instead of just saying "missing", you print a usage message showing how to run the program. This lets the user fix the mistake.
Example: printf("Usage: %s <file>\n", argv[0]);. Here argv[0] gives the program name so the message adapts to how the program was called. Keep the message short and clear: state the expected arguments' order and type. Well-designed usage messages are the backbone of tool documentation and steer users to the right command instead of trial and error.
Practice Write argument validation
Declare a simulated count with int argc = 1;. Check with if (argc < 2); if true, print printf("Hata: argüman eksik\n"); and return 1;. Otherwise print printf("Tamam\n"); and end with return 0;.
Starter code
#include <stdio.h>
// Define argc as 1
// If argc < 2, print error and return 1
// Otherwise print "Tamam"
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
int main(void) {
int argc = 1;
if (argc < 2) {
printf("Hata: argüman eksik\n");
return 1;
}
printf("Tamam\n");
return 0;
}Expected output
Hata: argüman eksik
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When is argc < 2 true?
- When the user gives no argument Correct answer
- When the user gives two arguments
- When the program fails to compile
- When argc equals zero
Explanation: argc < 2 is true when only the program name is present (no user argument).
2 Match the validation parts
| Term | Meaning |
|---|---|
argc < 2 |
Missing-argument check |
argv[0] |
Program name |
return 1 |
Error exit |
printf |
Message print |
3 Complete the error message
printf("Hata: eksik %d
", ____);
printf("Hata: eksik %d
", argc);
Explanation: Printing argc shows the cause of the error.