Main function
#mainfunction
In C the main function is called automatically whenever code is running.
#include <stdio.h>
#include <cs50.h>
int main(void)
{
}
(void)
- It means that the program is not taking any command line input as an argument
- (except make)
Programs that take command like arguments:
#include <stdio.h>
#include <cs50.h>
int main(void)
{
string s = get_string("What's your name? ");
printf("%s\n Hello, " , s);
}
But there are keywords such as argcand argv that can go inside the main function.
The main function takes 2 command-line arguments via argc and argv :
- argc is a counter that tells you how many "elements" there are in argv. That being said, argv is an array of string (char)* arguments that get passed to the program when calling it (from the console).
E.g. when you execute a program by calling:
program.exe
and don't add any arguments, argc will be 1 and argv will have exactly one element: argv[0], the name of your program.
So adding some arguments it might look something like :
program.exe -windowed -clean
Now argc is 3, argv[0] still is the program name, argv[1] and argv[2] would be:
"-windowed" and "-clean".
code:
#include <stdio.h>
#include <cs50.h>
int main(int argc, string argv[]){
// This program takes the input from the command line
printf("Hello, %s\n", argv[1] );
- If inside the
argvvariable is assigned 0, the print statement will print the program's name. This is because the 0 location, automatically will contain the program-s name. (Useful for self-referencing) - Same for
argc, it contains the total number of argument in the prompt, but the first is always the programs name.
The value that the main function returns , is called anexit status.
#include <stdio.h>
#include <cs50.h>
int main(int argc, string argv[]){
if (argc != 2)
{
printf("Missing CL argument\n");
return 1;
}
printf("Hello, %s\n", argv[1]);
return 0;
}
We can check secretly the return value of a program by digiting: echo $?
In C when a program returns the a value, the execution stops.