DEV Community

Haile Melaku
Haile Melaku

Posted on

C - argc, argv

Arguments on main are used to guide on how the program does it's job, when the programs are run in a hosted environment.
They are also used to pass the name of the file to the program.

A host environment is any OS environment that satisfy the basic requirement to be called an Operating system(os) like RAM, CPU, etc ..

Declaration of arguments on main is

int main(int argc, char *argv[]);
Enter fullscreen mode Exit fullscreen mode

Exit status is used to indicate that a program completed successfully (a zero value)(exit(0);) or some error occurred (a non-zero value).

argc : is the number of the arguments supplied to the program.
arv[] : is the array pointer of arguments given to the program.

In arv[] the last value of the array or arv[argc] is null('\0').


#argc and argv

Up until now we have seen that argc is the number of argument and arv[] is array pointer of all the argument that are written on the terminal.

A really good example of argc and argv is

gcc main.c -o main
Enter fullscreen mode Exit fullscreen mode

In this case the values gcc, main.c, -o and main are arguments that are passed to the gcc program using argv[].
the value of the arguments will be like

argc = 4
argv[0] = gcc
argv[1] = main.c
argv[2] = -o
argv[3] = main
argv[4] = null
Enter fullscreen mode Exit fullscreen mode

Example

Image description

Output

Image description

If we ever want to make an operation on the values of the parameter argv[] use the function atoi() to convert the string to an integer also don't forget to include the library #include <stdlib.h>.

Example

Image description
output

Image description

Tip: to skip unused variable type cast the variable to void like (void)UNUSED_VAR;.

Example
If a variable in the parameter like argc, argv[] or any other variable, let's say you didn't use argc variable in the code you can skip the error of unused variable like

(void)argc;

Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
pauljlucas profile image
Paul J. Lucas

The declaration should really be:

int main( int argc, char const *argv[] ) {
Enter fullscreen mode Exit fullscreen mode

You didn't mention that:

int main( int argc, char const **argv ) {
Enter fullscreen mode Exit fullscreen mode

is an alternate way to declare main() because "array parameters" simply don't exist in C.

You misspelled arv.

argv[argc] is not \0. \0 is the null character, not a null pointer. A null pointer is either NULL or the literal 0. Yes, it matters.

You also didn't mention that:

  • Exit status (on Unix variants, at least) have specific error codes.
  • In main(), exit() and return are equivalent.
  • In main(), exit() and return can be omitted in which case it's equivalent to exit(0).

Unused variables are just a warning, not an error (unless you do -Werror).

Lastly, you really shouldn't be compiling and running code as root.