C Structure and Function
C Structure and Function
and Function
Structure
a collection of variables of different data types under a
single name. It is similar to a class in that, both holds a
collection of data of different data types.
Struct
For example:
struct Person
{
The struct keyword defines a char name[50];
structure type followed by an int age;
float salary;
identifier (name of the };
structure).
Here a structure person is defined
which has three members: name,
age and salary.
Creating Struc #include <stdio.h>
struct Person {
// code
} person1, person2, p[20];
In both cases,
return 0;
}
Struct as
Function
Argument
You can pass a struct to a function as an
argument. This is done in the same way as
passing a normal argument. The struct variables
can also be passed to a function. A good
example is when you need to display the values
of struct members.
#include <stdio.h>
#include <string.h>
struct Person
{
int citizenship;
int age;
};
void func(struct Person p);
int main()
{
struct Person p;
p.citizenship = 1;
p.age = 27;
func(p);
return 0;
}
void func(struct Person p)
{
printf(" Person citizenship: %d\n",p.citizenship);
printf(" Person age: %d",p.age);
}
Limitation of a C++
Structure
• The struct data type cannot be
treated like built-in data types. • Static members cannot be
• Operators like + -, and others declared inside the
cannot be used on structure structure body.
variables. • Constructors cannot be
• The members of a structure can created inside a structure.
be accessed by any function
regardless of its scope.