I am trying to write a C program where based on the size of the member of the structure ,that many members should be read into an array.
As you can see in the below code,based on the value of the bookPtr->size
,I will add that many members into the array.
If bookPtr->size is 3 , I will read all the members x,y and z.
If bookPtr->size is 2 , I will read the members x and y.
If bookPtr->size is 1 , I will read the members x.
If bookPtr->size is 0 , no members are read.
But I want to optimize the code further.Is there a way so that code length is reduced.Thanks.
#include<stdio.h>
typedef struct
{
int x;
int y;
int z;
int size;
}Book;
void Get (Book* bookPtr)
{
Book mybook;
int size = bookPtr->size;
if(size == 3)
{
mybook->x = bookPtr->x;
mybook->y = bookPtr->y;
mybook->z = bookPtr->z;
}
else if(size == 2)
{
mybook->x = bookPtr->x;
mybook->y = bookPtr->y;
}
else if(size == 1)
{
mybook->x = bookPtr->x;
}
else
{
}
}
int main()
{
Book bookPtr;
bookPtr.x = 2 ;
bookPtr.y = 2 ;
bookPtr.z = 20 ;
bookPtr.size = 2 ;
Get(&bookPtr);
return 0;
}