How do Functions and Data Structures work?

In the Data Structures section of the tutorial, I noticed in the movie example that the function's parameter:
1
2
3
4
5
void printmovie (movies_t movie)
{
  cout << movie.title;
  cout << " (" << movie.year << ")\n";
}

is using the same name of the Structure. Usually, a function uses an arbitrary name for it's parameter and it's type, no? eg.:
1
2
3
4
add(int varA, int varB)
{
    return (varA + varB)
}
I understand that the use of void changes things, but I don't understand why you would do that when using Structures.
Last edited on
Parameters, just like all variables, should have useful, descriptive names that clearly tell you what they are used for. In the case of your add function (which by the way needs to return an int, you left out the return type), it is obvious that varA will be added to varB. But what if you don;t know what a function does, or what its parameters should be?What if you only have a declaration like this?
int Func(int a, int b, int c);
Is this function clear as to what it does?

What about this function?
int Func(int min, int max, int val);
Is it clear that this function clearly returns a version of val that is within the range min, max? Could you deduce this from the function where the names of the parameters were a, b, and c?

it is important to be clear at all times ;)
I noticed in the movie example that the function's parameter...is using the same name of the Structure


This:

1
2
3
4
struct movies_t {
  string title;
  int year;
} mine, yours;


creates a type called movies_t (and two variables 'mine' and 'yours' of type movies_t).

The parameter of the printmovie function is called 'movie' of type movies_t. Thus the parameter is not using the same name as the struct.
To use this kind of thing @shacktar, would you do something like:
1
2
movies_t.title = "Iron Man 2";
movies_t.year = 2012;

? I am also curious about how structs work, and I don't see what mine/yours does. Could you please explain it to me?
No, you couldn't do that unless title and year were static members, and then you would use the scope resolution operator ::. For this struct you would have to create instances of it (in this example the there are already two objects called mine and yours). You could then say
1
2
movie.title = "Iron Man 2"; 
movie.year = 2012;                       // this isn't true, where did you get your dates xD 

or
1
2
yours.title = "Forest Gump"
yours.year = 1994;


Read the section of this websites tutorial on structures: http://cplusplus.com/doc/tutorial/structures/
Last edited on
Ohh I get it now :). But I can only use the variables you put in after the brackets? And lul I just put in a random date and movie.
You can use the variables after the bracket, or you can make more movies:
1
2
movie_t Gone_With_The_Wind;
movie_t Super_8;
Topic archived. No new replies allowed.