Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we leave some structure variables out of the curly brackets?

Tags:

c

I'm trying to understand struct in C. I couldn't get the idea about this definition below. Why do we leave aCard, deck[ ] and *cardPtr out? What is the difference between including them in and leaving them out?

 struct card {
    char *face;
    char *suit;
 } aCard, deck[52], *cardPtr;
like image 986
Belverus Avatar asked Oct 17 '18 09:10

Belverus


People also ask

Why we use curly parenthesis not any other brackets?

Curly braces indicates the block of statements in C programming language. The function in C has braces in its syntax. But one can put braces where logically related statements are written. A single statement in loop or if-else block need not be written within braces.

What is the purpose of curly brackets?

In writing, curly brackets or braces are used to indicate that certain words and/or sentences should be looked at as a group.

What is the purpose of curly brackets in Java?

Different programming languages have various ways to delineate the start and end points of a programming structure, such as a loop, method or conditional statement. For example, Java and C++ are often referred to as curly brace languages because curly braces are used to define the start and end of a code block.

Why do we use block of statements with braces?

Braces improve the uniformity and readability of code. More important, when inserting an additional statement into a body containing only a single statement, it is easy to forget to add braces because the indentation gives strong (but misleading) guidance to the structure.


2 Answers

You are mixing things up. A struct card has the members face and suit. But there are three variables using the struct card type, namely aCard, deck, cardPtr.

Alternatively one could have written:

typedef struct {
    char *face;
    char *suit;
} Card;

Card aCard, deck[52], *cardPtr;
// or even
Card aCard;
Card deck[52];
Card *cardPtr;

For the typedef have a look at: Why should we typedef a struct so often in C? (It goes into the typedef struct { ... } Foo; vs struct Foo {...} debate).

like image 139
Micha Wiedenmann Avatar answered Oct 26 '22 08:10

Micha Wiedenmann


Your piece of code could be written like this which makes it clearer:

struct card {          // define the struct card
    char *face;
    char *suit;
 };

struct card aCard;     // declare a variable "aCard" of type "struct card "
struct card deck[52]   // declare an array of 52 variables of type "struct card"
struct card *cardPtr;  // declare a variable "cardPtr" of type "pointer to struct card"
like image 27
Jabberwocky Avatar answered Oct 26 '22 07:10

Jabberwocky