0
0
Cprogramming~5 mins

Accessing arguments

Choose your learning style9 modes available
Introduction

We use arguments to give extra information to a program when it starts. Accessing arguments lets the program read these inputs and use them.

When you want to tell a program which file to open without changing the code.
When you want to set options or modes for a program before it runs.
When you want to pass numbers or words to a program to process.
When you want to make one program work differently depending on what the user types.
When you want to automate tasks by giving instructions through arguments.
Syntax
C
int main(int argc, char *argv[]) {
    // code here
}

argc is the count of arguments including the program name.

argv is an array of strings holding each argument.

Examples
This shows the basic way to access arguments in C.
C
int main(int argc, char *argv[]) {
    // argc is number of arguments
    // argv[0] is program name
    // argv[1] is first argument
}
This prints the first argument if it exists.
C
#include <stdio.h>

int main(int argc, char *argv[]) {
    if (argc > 1) {
        printf("First argument: %s\n", argv[1]);
    }
    return 0;
}
Sample Program

This program prints how many arguments were given and lists each one. The first argument is always the program name.

C
#include <stdio.h>

int main(int argc, char *argv[]) {
    printf("Number of arguments: %d\n", argc);
    for (int i = 0; i < argc; i++) {
        printf("Argument %d: %s\n", i, argv[i]);
    }
    return 0;
}
OutputSuccess
Important Notes

Arguments are always strings; you may need to convert them to numbers if needed.

Remember that argv[0] is the program's name or path.

Always check argc before accessing argv to avoid errors.

Summary

Arguments let you give input to a program when it starts.

Use argc and argv in main to access them.

Check the number of arguments before using them to keep your program safe.