jeudi 26 février 2015

Clarity between functions in C

I understand the concept of functions, really but I'd like to understand more of the differences between them. It seems like there are 4 variations of using functions in C:



  1. Those that require parameters and do NOT return a value

  2. Those that require parameters and do return a value

  3. Those that do NOT require parameters and do return a value

  4. Those that do NOT require parameters and do NOT return a value (I have used these mostly in BASH scripting


I understand what all of them do but just a bit confused. It mainly has to do with the first 3 (I get the last one as its simple).


When would a programmer use either of the first three functions? I have a couple here that use structures but just not sure why their are written the way they are:



struct employee read_emp()
{
struct employee x;

printf("Please enter the address: ");
scanf("%s", &x.address);

return x;
}


print_emp(struct employee y)
{
printf("Address is %s\n", y.address);
}


Then it is called like this:



main()
{
struct employee emp1, emp2;

emp1 = read_emp();
print_emp(emp1);
}


So the print_emp() function uses as a parameter, another function which is the read_emp() function. This confuses me quite a bit. The first function read_amp() does not take any parameters but it was required to define a type before defining it as so: struct employee read_emp(). then a struct variable is initialized and it returns a value. Now whenever we call this function, a parameter is not needed, I understand that. What does come back from calling the function would be the result, which is whatever was entered from the keyboard. Got that.


However, the function below it does NOT take any type definition such as struct employee before print_emp(). Also no variables are initialized and no return value is needed. However, it takes a parameter as a structure variable declaration. why here and not in read_emp()?


The read_emp() function is an example of a function in the list I stated as number #3 The print_emp() function is an example of a function in the list I stated as number #1


Function from the list number #2 seems self-explanatory as well: Here is an example I understand:



float average(int n1, int n2, int n3)
{
return (n1 + n2 + n3) / 3;
}


It's easy to understand this because it takes 3 parameters and returns a value. Thus when we call it in main(), it would look like this (assuming main has another input function or section where we read in 3 numbers for the user's keyboard:



average(num1, num2, num3);


I just don't get why read_emp() takes no parameters and returns a value, and print_emp() is the opposite and takes as parameter a declaration of a structure variable. Why wouldnt read_emp() do that too? Any help would be appreciated. Thanks.


Aucun commentaire:

Enregistrer un commentaire