Parameters, functions in C

0

I'm a beginner in programming and I have a lot of questions regarding functions and parameters. Here is an example code:

#include math.h

int main(int argc, char *argv[]) // Dúvida nessa linha    
{           
    double x1, x2, y1, y2, d; 

    double v; 

    scanf("%lf, %lf, %lf, %lf", &x1, &y1, &x2, &y2); 

    v = (x1-x2)*(x1-x2) + (y1-y2)*(y12-*y2); 

    d = sqrt(v); 

    printf("Distância: %f", d); 

    return 0;     
} 

Doubt: What do these parameters indicate in this code? When and why should the parameters be used?

    
asked by anonymous 13.10.2016 / 00:15

2 answers

0

The parameters of the main function allow access to arguments passed by the command line to the program. For example, the sample program could be modified to receive the calculation numbers by command line. If you want the program call to be:

> dist.exe 10 10 50 60

The program could be modified like this:

#include <stdio.h> 
#include <math.h>
#include <stdlib.h> 

int main(int argc, char *argv[]) // Dúvida nessa linha    
{           
    double x1, x2, y1, y2, d; 

    double v; 

    x1 = atof( argv[1] );
    y1 = atof( argv[2] );
    x2 = atof( argv[3] );
    y2 = atof( argv[4] );

    if (argc != 5)
        printf("Erro: eram esperados 4 parâmetros");

    v = (x1-x2)*(x1-x2) + (y1-y2)*(y12-*y2); 

    d = sqrt(v); 

    printf("Distância: %f", d); 

    return 0;     
} 

argc indicates the number of command line arguments, plus 1. This 1 is there because the name of the program itself is taken into account as well.

argv is an array that contains the parameters themselves. In the previous call example these parameters would be:

argc = 5;
argv = { "dist.exe", "10", "10", "50", "60" };
    
13.10.2016 / 00:37
1

argc (argument count) and argv (argument vector) are arguments that are passed by the command line to the main function in C and C ++. argc is the amount of string sent by the command line and argv is where the string is contained.

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main(int argc, char *argv[]) {
    printf("\nVoce passou %d elementos pela linha de comando.\n\n", argc);
    puts("Inprimindo os argumentos\n");
    int i;
    for(i = 0; i < argc; i++) {
        printf("%s\n", argv[i]);
    }
    putchar('\n');
    return EXIT_SUCCESS;
}

Compiling the program with gcc on the windows command line:

gcc HelloWorld.cpp -o HelloWorld

After this, the executable will be generated: HelloWorld.exe

Now just run the HelloWorld.exe executable from the command line and pass the arguments

HelloWorld 10 20 30 Ola Test

Result:

Voce passou 6 elementos pela linha de comando.

Inprimindo os argumentos

HelloWorld
10
20
30
Ola
Test
    
13.10.2016 / 00:33