Posted in All Posts, Semester 2

Structure Syntax in C

We saw what are structures in the previous post. Now, we’ll learn syntax to use structures efficiently in C.

Declaring Structure Variables

Below is an example to demonstrate declaration of structure variables.

In the above definition of the structure book, there are two variables of the type struct book – book1 & book2 but they are declared in two different ways.

  1. With definition : After the closing curly bracket (}) and before the semicolon (;).

  2. After definition : Write struct keyword along with the structure name (tag name) and then variables you want to declare. Separate them with commas and end the statement with a semicolon.

Structures allows user to define his own data type!
To declare a variable, we write ‘data_type variable_name;
We used the same format here to declare the variable book2. Here struct book is a data type and book2 is the variable name!

Accessing structure variables

We can access and assign values to members of a structure in a number of ways. We know that the members are not variables, so they have to be accessed through the structure variable.
For example, the word ‘title‘ has no meaning whereas the phrase ‘title of book 1‘ has a meaning.
To make a link between variable and member, member operator.‘ has to be used. The member operator is also called dot operator or period operator.
For example, book1.price
is the variable representing the price of book1 and can be treated like any other ordinary variable.

Did You Know? Assigning a tag name to a structure is not necessary when you declare structure variables with the structure definition! Tag name is only useful for declaring variables.

Assigning Values

Now let’s look at how to assign values to member variables of book1:

Initializing structure variables

Like any other data type, a structure variable can be initialized at compile time.

As you saw, you just have to put desired values in the curly braces in the sequence of the member variables.

Rules for Initialization

  • Individual members can not be initialized.
  • Partial initialization is allowed, i.e. we can assign values to only first few members and then leave remaining blank.
  • The uninitialized members will be assigned to default values as below-
    1. Zero for integer and floating point numbers.
    2. ‘\0’ for characters and strings.

We hope that you found this article to be helpful.
Please share your thoughts in the Comments Section.

If you liked this article, then please like our Facebook page.

Learn about Arrays of Structures.

Suggested Reading

Comment your thoughts

This site uses Akismet to reduce spam. Learn how your comment data is processed.