Parameters, functions in C

Asked

Viewed 105 times

0

I am a beginner in programming and I have a lot of doubt about the functions and the parameters. Follow a code example:

#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;     
} 

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

2 answers

1

argc (argument Count) and argv (argument vector) are arguments that are passed from 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 that, 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

Upshot:

Voce passou 6 elementos pela linha de comando.

Inprimindo os argumentos

HelloWorld
10
20
30
Ola
Test

0


The parameters of the function main allow access to arguments passed per command line to the program. For example, the sample program could be modified to receive the calculation numbers per command line. In case you want the call from the show 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 specifies the number of command line arguments, plus 1. This plus 1 is there because the program name is also taken into account.

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" };

Browser other questions tagged

You are not signed in. Login or sign up in order to post.