Extra 5% OFF Use Code: OL05
Free Shipping over ₹999

Function Arguments

Function Argument

If a function is to use arguments, it must declare variables that accept the values of the arguments. These variables are called the formal parameters of the function. They behave like other local variables inside the function and are created upon entry into the function and destroyed upon exit.

As shown in the following function, the parameters are declared inside the parentheses following the function name. The declaration consists of the parameter type, followed by the parameter name. For example:

int add(int a, int b) {
  return a + b;
}

In the above example, the function add takes two integer parameters a and b.

When a function is called, the arguments are passed as values or references to the corresponding parameters. For example:

int result = add(2, 3);

In this example, the function add is called with two integer arguments, 2 and 3, which are passed to the parameters a and b respectively.

In C, there are several ways to pass arguments to a function, including call by value, call by reference. The choice of passing mechanism depends on the specific requirements of the function and the program.

argc and argv Arguments to main()

Sometimes it is useful to pass information into a program when you run it. Generally you pass information into the main() function via command line arguments.

There are two special built in arguments, argv and argc, that are used to receive command line arguments.

  • argc is an integer that represents the number of command-line arguments passed to the program. The first argument, argv[0], is always the name of the program itself.
  • argv is an array of strings or an array of pointers to characters, where each element is a command-line argument passed to the program. The command-line arguments are separated by spaces.

Here’s an example program that demonstrates how to use argc and argv:

#include <stdio.h>

int main(int argc, char *argv[]) {
    printf("Number of command-line arguments: %d\n", argc);

    printf("Command-line arguments:\n");
    for (int i = 0; i < argc; i++) {
        printf("%d: %s\n", i, argv[i]);
    }

    return 0;
}

If we compile this program and run it with command-line arguments, we’ll see output like this:

$ gcc example.c -o example
$ ./example foo bar baz
Number of command-line arguments: 4
Command-line arguments:
0: ./example
1: foo
2: bar
3: baz

In this example, we pass three command-line arguments to the program: foo, bar, and baz. The program prints out the number of arguments (4, including the program name), and then prints each argument and its index.

    Leave a Reply

    Your email address will not be published.

    Need Help?