Skip to study material
← Question index

QUESTION 16

Explain argc and argv with a checked numeric-argument example.

5 marks

Answer in brief

Command-line arguments let a user supply input when starting a program rather than through later keyboard reads.

Main form

int main(int argc, char *argv[])

Argument handling

The example requires exactly two user-supplied numeric strings, so it checks argc == 3 before using argv[1] and argv[2]. Accessing a missing argument is invalid. The shell’s quoting rules affect how spaces are grouped before the program receives its arguments.

Numeric conversion

Use strtol with an end pointer and errno checking. A successful conversion must consume at least one character, end at the string terminator and avoid ERANGE. Then check the application range before converting to int. atoi does not provide the same reliable error-reporting interface.

Example

Running the compiled program with arguments 12 and 8 prints Sum = 20. Supplying abc or an unsupported value reports invalid arguments. The sample accepts values from -10000 through 10000, making their sum safe even within the minimum int range required by C.

Complexity and usage

Parsing strings of lengths m and n takes O(m + n) character work. The program needs only fixed conversion variables. The online single-file compiler may not expose a command-line-argument field; use a terminal with the shown compile/run command when that option is unavailable.

Complete C example

main.c

Download main.c
/* CodeBhavya | Data Structures AR25 | Learning example */
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
int read_number(const char *text, int *out)
{
    char *end;
    errno = 0;
    long value = strtol(text, &end, 10);
    if (end == text || *end != '\0' || errno == ERANGE || value < -10000 || value > 10000) { return 0; }
    *out = (int)value;
    return 1;
}
int main(int argc, char *argv[])
{
    int a, b;
    if (argc != 3 || !read_number(argv[1], &a) || !read_number(argv[2], &b)) {
        puts("Usage: program integer integer (-10000..10000)"); return 1;
    }
    printf("Sum = %d\n", a + b);
    return 0;
}

Compile and run

gcc -std=c11 -Wall -Wextra -pedantic main.c -o program
./program 12 8

In Windows PowerShell, use program.exe as the output name and .\program.exe to run it.

Sample input and output

The example uses values in the code and the shown command-line arguments.

Output

Sum = 20