Reputation: 21
I have a sample piece of code and I had a question about it. Here is the code. My questions are comments near the bottom of the code and I was wondering if anyone could help out. Getting mixed up here.
#include <stdio.h>
#include <string.h>
struct car {
char make[30];
char model[30];
int year;
};
struct car f(struct car c);
int main(void)
{
struct car c1 = {"Ford", "Mustang", 2014}, c2;
c2 = c1;
printf("%s, %s, %d\n", c1.make, c1.model, c1.year);
c2 = f(c1);
printf("%s, %s, %d\n", c2.make, c2.model, c2.year);
}
struct car f(struct car c) /* Is car here referring to the structure at the very top
of the program, so it knows what structure to put it? */
{
struct car temp = c; /* What exactly is c in this function and why copy it? */
strcpy(temp.model, "Explorer");
temp.year += 5;
return temp;
}
The code prints:
Ford, Mustang, 2014
Ford, Explorer, 2019
Upvotes: 1
Views: 83
Reputation: 84652
struct car f(struct car c) /*is car here refering to the structure at the very top
of the program, so it knows what structure to put it?/*
struct car
here is a type 'struct car' defining X
. The struct car
at the top defines the global type struct car
. X
refers to the function f
that provides a return of type struct car
and c
an argument that expects a reference of type struct car
(regardless what name it has). The struct car at the top has global scope, the function above expect an agrument such as c1
or c2
declared in main().
Upvotes: 0
Reputation: 1533
When you call f()
the struct is copied and then passed in to the function. Any modifications made in the function will be discarded upon exit. However, you are passing out a struct which you then save and print. So, to answer your question, the struct car
in the function is a temporary variable that does not directly refer back to anything external to the function.
If you want to directly modify a variable outside the function, then you will need to pass a pointer instead and dereference that pointer inside the function.
Upvotes: 1
Reputation: 6224
struct car
is a type, which is defined at the top of your program. So struct car f(struct car c)
is a function named f
that takes a struct car
named c
as a parameter, and returns another struct car
.
The reason to make a copy of c
is so that you can change one of them without affecting the other. Since you passed c
by value in this case, it doesn't really matter; you could edit c
and then return it. But if you'd passed it by reference (ie, passing a pointer to it), then modifying it would change the caller's copy, which might not be what you want.
Upvotes: 4