Angel
6/11/2011 8:42:00 PM
On 2011-06-11, Keith Thompson <kst-u@mib.org> wrote:
> Angel <angel+news@spamcop.net> writes:
>> On 2011-06-11, Ya Shou <zxyzxy12321@gmail.com> wrote:
> [...]
>>> Enumeration defines constants used in c++, but not seen any in c, why?
>>
>> It's mainly historical. Enums were originally not a part of the C
>> language when K&R designed it; they were first added in C89. Many
>> sources still use #defines over enums, and both forms are acceptable
>> as in C there is functionally very little difference between them.
>
> Enums are older than that. If I recall correctly, they were added
> shortly after K&R1, which was published in 1978.
I was going by Wikipedia, which claims it was first introduced by ANSI.
But it is quite possible that you are right. I was only five back then
so I don't remember 1978 too well. ;-)
> One drawback of enums is that they're only of type int; you can't use
> them to define constants of other types, including floating-point types.
Very true.
> Arguably using an enum to define a single constant:
>
> enum { max = 1000 };
>
> is an abuse of the feature, which is intended to be used to define a
> group of closely related constants. Of course that stop me from using
> it that way.
Yeah, I tend to use enums to define groups of closely related constants,
like the byte offsets in my program to parse Infinity Engine files, which
looks like this:
// Constants to help parse header blocks of *.itm files v1 and v1.1.
enum item_v1
{
itm_v1_signature = 0x0000,
itm_v1_version = 0x0004,
itm_v1_generic_name = 0x0008,
itm_v1_specific_name = 0x000c,
[...]
itm_v1_size = 0x0072,
};
That replaces that ugly, non-portable packed structure I first used.
> What I'd really like to see is for C to adopt C++'s feature, where
> a const object of numeric type whose initializer is a constant
> expression can be used as a constant:
>
> const int max = 1000;
> const double pi = 3.14159265358979;
>
> But it's probably too late to add that to C201X.
Yeah, #defines and macros have their place, but this seems like a much
more natural way to define a numerical constant to me.
--
"C provides a programmer with more than enough rope to hang himself.
C++ provides a firing squad, blindfold and last cigarette."
- seen in comp.lang.c