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;
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.
In writing, curly brackets or braces are used to indicate that certain words and/or sentences should be looked at as a group.
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.
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.
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).
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With