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[]);
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
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
Example
Output
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
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;
Top comments (1)
The declaration should really be:
You didn't mention that:
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 eitherNULL
or the literal0
. Yes, it matters.You also didn't mention that:
main()
,exit()
andreturn
are equivalent.main()
,exit()
andreturn
can be omitted in which case it's equivalent toexit(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.