imad wrote
(in article
<
[email protected]>):
Note to Google: I hate you.
Back to our regularly scheduled thread... please learn how to
use the google interface to include context.
Since it will be easier to manage, also both kinds of data will be
present in the same file, so it will be more convenient to view any
kind of data about the file since everything is present in a single
structure.
If it actually was easier, then you wouldn't be asking these
questions. "Less code" and "easier" are not the same thing
necessarily.
You said upthread:
The thing is I will be using the structure for parsing a compressed
file. If the compressed data is of say TYPE A I shall use only two
elements. If it is of say TYPE B, I will be using all the three. For
reasons of efficiency, I don't want to use the third element. And I
will be using array of the same structure for storing the information.
So using #ifdef is out of question, since I will have to declare the
array in the beginning itself. Also, by using pointers I will still
have a third dummy variable which again is not needed for TYPE A.
This sounds like some poorly thought out design decisions. If
you have two different types of file data, trying to mash them
into one may not be the best answer. If you really want to
carry both types around in the same containers, then you need a
conditional structure with a flag value to indicate if the "TYPE
B" data is present.
Going back to your original,
#define TYPE_A 0x00
#define TYPE_B 0x01
struct dummy
{
int a;
int b;
int c; /* valid only for TYPE B */
int my_type; /* indicates validity of c entry */
};
When you read in the data, you determine which TYPE it is, set
the appropriate values in the struct, and copy it into your
array. The problem is, every time you use the data, you have to
check/set the my_type entry. That is the cost of smashing two
different TYPES (not C types) into one container. If you reuse
array entries over time, you'll also have to make sure that the
my_type field is updated properly as needed.
On the other hand, if you know for a fact that values for 'c'
have a limited number of possible values, you might be able to
simplify it a bit by using a reserved value (that can not occur
in your data set) for c. This would allow you to set c =
MAGIC_NUMBER in the cases of a TYPE_A data read and eliminate
the extra struct entry, but you still have to manage it
carefully and check the value of c all of the time.