[C] struct initialization, swap

  • initialization
#include <stdio.h>

typedef struct Book
{
        char title[30];
        char author[20];
        int series;
}Book;

int main(void)
{
        Book b1 = {"Harry Potter", "J. K. Rowling", 7}, b2 = {"The Lord of the Rings", "J. R. R. Tolkien", 3};

        puts("--------------------");
        puts(" * struct * ");
        puts("--------------------");

        printf(" b1 : %10s %26s %7d books \n", b1.title, b1.author, b1.series);
        printf(" b2 : %10s %20s %4d books \n", b2.title, b2.author, b2.series);

        return 0;

        /*
        --------------------
        * struct *
        --------------------
        b1 : Harry Potter              J. K. Rowling       7 books
        b2 : The Lord of the Rings     J. R. R. Tolkien    3 books
        */
}
  • swap
#include <stdio.h>

typedef struct Book
{
        char title[30];
        char author[20];
        int series;
}Book;

int main(void)
{
        Book b1 = {"Harry Potter", "J. K. Rowling", 7}, b2 = {"The Lord of the Rings", "J. R. R. Tolkien", 3};
        Book tmp;

        puts("--------------------");
        puts(" * before struct swap * ");
        puts("--------------------");

        printf(" b1 : %10s %26s %7d books \n", b1.title, b1.author, b1.series);
        printf(" b2 : %10s %20s %4d books \n", b2.title, b2.author, b2.series);
        puts("----------------------------------");
        tmp = b1;
        b1 = b2;
        b2 = tmp;

        puts(" * after swap * ");
        printf(" b1 : %10s %20s %4d books \n", b1.title, b1.author, b1.series);
        printf(" b2 : %10s %26s %7d books \n", b2.title, b2.author, b2.series);

        return 0;

        /*
        --------------------
        * before struct swap *
        --------------------
        b1 : Harry Potter              J. K. Rowling       7 books
        b2 : The Lord of the Rings     J. R. R. Tolkien    3 books
        ----------------------------------
        * after swap *
        b1 : The Lord of the Rings     J. R. R. Tolkien    3 books
        b2 : Harry Potter              J. K. Rowling       7 books
        */
}

Reference

Tags:

Categories:

Updated: