Structure Assignment 5 — Initialize and Display the Details of a Book
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Initialize and Display the Details of a Book Using a Structure

📑 On this page:
  • Filling a book in one line
  • The two ways to fill it
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • How to fill a struct at the same line where you declare it
  • Why the order of values in the braces has to match the members
  • How to use names like .title = ... so the order stops mattering
  • What happens to any member you forget to set
  • How to print a book record so it looks tidy on screen

Filling a book in one line

In the last assignment we set each field of the book one by one — first the title, then the author, then the price. That works, but C gives you a shortcut. You can fill the whole struct on the same line where you declare it, by putting the values inside curly braces. The compiler reads them left to right and drops each one into the matching field.

So instead of three lines of strcpy and assignment, you get one line: struct book b = {"The C Programming Language", "Kernighan & Ritchie", 45.99};. That's it. The title goes into title, the author goes into author, and the price goes into price — simply because that's the order the members were written in the struct.

There is a catch, though. This shortcut depends on the order. If you later move price above title in the struct, the same line will silently put 45.99 into the wrong slot and give you garbage. That's why C99 added a second style where you name each field: {.title = "...", .author = "...", .price = 45.99}. With names, the order doesn't matter and the code still works if the struct is rearranged. We'll show both here.

💡 In one line: struct book b = {"Title", "Author", 45.99}; fills the fields in order, and {.title="Title", .author="Author", .price=45.99} fills them by name.

Two boxes side by side. On the left, values in order: title, author, price. On the right, the same values but each one labelled with .title, .author, .price.

The two ways to fill it

Here are the two styles next to each other. Both produce the same book — pick whichever feels clearer to you, but stick with one across your program.

/* Style 1: values in the same order as the members */
struct book b = {
    "The C Programming Language",
    "Kernighan & Ritchie",
    45.99f
};

/* Style 2: names on each value (C99) */
struct book c = {
    .title  = "The C Programming Language",
    .author = "Kernighan & Ritchie",
    .price  = 45.99f
};
                                

The first style is shorter. The second is safer. If you're learning, the first is fine. If you're writing code that someone else might edit later — or code you'll come back to in six months — the second is nicer because it says out loud what each value is for.

Style Example Good for Watch out for
In order {"Title", "Author", 45.99f} Short programs, old compilers Breaks if members are reordered
By name {.title="Title", .author="Author", .price=45.99f} Real projects, long structs Needs C99 or later (all modern compilers)

Complete C Program

Program: fill a book struct and print it

#include <stdio.h>

struct book {
    char  title[100];
    char  author[50];
    float price;
};

int main(void) {
    struct book b = {
        "The C Programming Language",
        "Kernighan & Ritchie",
        45.99f
    };

    printf("Book Record\n");
    printf("-----------\n");
    printf("Title  : %s\n", b.title);
    printf("Author : %s\n", b.author);
    printf("Price  : %.2f\n", b.price);

    return 0;
}
                                    

And here's the same program with names on the fields. If you compare them side by side, the only difference is the initializer — the printing part is identical.

Variant: same program with field names

#include <stdio.h>

struct book {
    char  title[100];
    char  author[50];
    float price;
};

int main(void) {
    struct book b = {
        .title  = "The C Programming Language",
        .author = "Kernighan & Ritchie",
        .price  = 45.99f
    };

    printf("Book Record\n");
    printf("-----------\n");
    printf("Title  : %s\n", b.title);
    printf("Author : %s\n", b.author);
    printf("Price  : %.2f\n", b.price);

    return 0;
}
                                    

Both versions compile with any modern C compiler and print the same thing. For the assignment, the first one is fine — it's shorter and easier to type. But it's worth knowing the second style, because you'll see it a lot in real C code.

Program Output

Book Record
-----------
Title  : The C Programming Language
Author : Kernighan & Ritchie
Price  : 45.99
                                

Nothing new in the output — it's the same record we printed in the last assignment, just filled in with a shorter line of code. Try swapping the title for your own favourite book and re-running. Then try leaving off the author to see what happens. You should see the author slot printed as an empty string, because a char array that you don't fill gets zeroed out.

Step-by-Step Explanation

This program is short, so let's walk through the parts that actually matter.

1. The struct itself

Same as before: title is a 100-character array, author is a 50-character array, and price is a float. Don't forget the semicolon after the closing brace — you'll get a confusing error message from the compiler if you do.

2. The one-line fill

struct book b = {"The C Programming Language", "Kernighan & Ritchie", 45.99f}; does everything at once. The compiler copies the first string into title, the second into author, and puts 45.99 into price. Notice the little f on 45.99f — that just means "this number is a float". Without the f, C would treat it as a double, which is a slightly bigger type, and it would quietly convert it down. Not a bug, but the f keeps things tidy.

3. What happens if you forget a value

Let's say you write struct book b = {"The C Programming Language"}; and stop there. The title gets filled, but author and price are left over. C guarantees they'll be set to zero — the author becomes an empty string, and the price becomes 0.0. That's actually useful: it means you don't have to worry about random garbage in the fields you didn't set. Handy for defaults.

4. Why the order matters in the first style

The values go into the fields in the order the fields appear in the struct. Since the struct says title first, author second, price third, that's the order the values have to come in. If you swapped the struct definition so price came first, the same line would put "The C Programming Language" into price — which wouldn't even compile, because you can't put a string into a float. But if the types happened to line up, you'd get silently wrong data. This is exactly the kind of bug that bites you at 2 AM.

5. Why the second style avoids that bug

With names on the values, the compiler matches each value to its field by name, not by position. So if you reorder the struct, the same line still fills the right fields. You can even write them in a different order yourself: {.price = 45.99f, .title = "...", .author = "..."} works just fine. The compiler sorts them out.

6. Printing the record

This part is identical to the last assignment. %s for the two strings, %.2f for the price with two decimal places. The dashes and labels are just for looks — the compiler doesn't care — but they make the output readable, which is the whole point of a "display" program.

🎯 Remember this: you can fill a struct at the moment you declare it, using braces. Values in the braces go to fields in order. Put names on them (.field = value) if you want to be safe against reordering. Anything you leave out is set to zero.

Frequently Asked Questions

1. Can I fill the struct with braces after declaring it?

No. The brace form only works on the same line where you declare the variable. Once b exists, you have to set each field by name — strcpy(b.title, ...); b.price = 45.99;. If you want to reset a struct later, you can assign another whole struct to it, or use memset to zero it out and then set the fields you want.

2. What does the f after 45.99 do?

It tells the compiler "this number is a float, not a double." Without it, 45.99 is a double, and the compiler quietly converts it down when storing into the float price field. The result is almost always fine, but you may get a warning with some warning flags turned on. Adding f says "yes, I really mean a float".

3. What if I leave out a field?

The field is set to zero automatically. So a missing author becomes an empty string, and a missing price becomes 0.0. This is guaranteed by the C standard for structs that have an initializer list — you can rely on it. It's a handy way to set defaults when you only care about some of the fields.

4. Can I mix the two styles in one initializer?

Yes, technically. struct book b = {"Title", .author = "Author", .price = 45.99f}; is legal — the first value goes into title by position, and the rest go by name. But it's confusing and error-prone. Most people pick one style and stick with it. If you're going to use names for one field, use them for all of them.

5. Does the brace style work with arrays of books?

Yes. You can write struct book library[3] = { {"Book 1", "Author 1", 10.0f}, {"Book 2", "Author 2", 20.0f}, {"Book 3", "Author 3", 30.0f} }; and each inner brace fills one book. That's the next assignment — total price of a collection of books — so this pattern shows up right away.

6. Is it safe to use the in-order style in real code?

For small structs where the order is obvious, yes. For larger structs — anything with more than four or five fields — I'd use names. The in-order style has one quiet problem: it breaks without any error message if someone reorders the struct members. That's exactly the kind of bug that takes hours to track down. The named style is one extra character per field and saves you that trouble.

💡 Tip: After this, try changing the order of the members in the struct — say, put price first. Re-run the in-order version and see what happens. Then switch to the named version and try the same change. One of them will break; the other won't. That's the whole argument for using names, in one experiment.

📖 Related Tutorials

  • 4. Create a Structure to Represent a Book
  • 6. Find the Total Price of a Collection of Books Using a Structure
  • 2. Initialize and Display the Details of a Student Using a Structure
  • Structure Initialization in C
  • Accessing Structure Members
  • Defining a Structure
  • Array of Structures
  • All 25 Structure Assignments

Previous Topic: -->> 4. Create a Structure to Represent a Book   ||   Next Topic: -->> 6. Find the Total Price of a Collection of Books Using a Structure


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.