I review my study book yesterday. While I was examing a program in the book as you can see below, I noticed something strange. We normally know that we cannot assign data to a variable defined as const type. Namely;
It represents that Constant Pointer - Non Constant Data.
Code:
const int *const z;
It represents that Consant Pointer - Constant Data.
It represents that Non Constant Pointer - Constant Data.
It represents that Non Constant Pointer - Non Constant Data.
-Constant pointer means that we cannot modify pointer variable.(value inside pointer variable)
-Constant Data means that we cannot modify data inside a variable which is pointed by a pointer variable.
So how can we assign a data to a const member of a structure in the following code,despite of being constant data?
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct card{
const char *face; // CONST MEMBER!!!!!!!!!!!!!!!CONST DATA!!!!!!!!!!!!!!!
const char *suit; // CONST MEMBER!!!!!!!!!!!!!!!CONST DATA!!!!!!!!!!!!!!!
};
typedef struct card Card;
void fillDeck(Card *const wDeck,const char *wFace[],const char *wSuit[]);
void shuffle(Card *const wDeck);
void deal(const Card *const wDeck);
int main()
{
Card deck[52];
const char *face[]={"Ace","Deuce","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Jack","Queen","King"};
const char *suit[]={"Hearts","Diamonds","Clubs","Spades"};
srand(time(NULL));
fillDeck(deck,face,suit);
shuffle(deck);
deal(deck);
return 0;
}
void fillDeck(Card *const wDeck,const char *wFace[],const char *wSuit[])
{
int i;
for(i=0;i<=51;i++){
wDeck[i].face=wFace[i%13]; // ASSIGN DATA TO A CONST MEMBER OF A STRUCTURE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
wDeck[i].suit=wSuit[i/13]; // ASSIGN DATA TO A CONST MEMBER OF A STRUCTURE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
}
}
void shuffle(Card *const wDeck)
{
int i;
int j;
Card temp;
for(i=0;i<=51;i++){
j = rand()%52;
temp = wDeck[j];
wDeck[j] = wDeck[i];
wDeck[i] = temp;
}
}
void deal(const Card *const wDeck)
{
int i;
for(i=0;i<=51;i++){
printf("%5s of %-8s%s",wDeck[i].face,wDeck[i].suit,(i+1)%4 ? " " : "\n");
}
}
OUTPUT: