hi,
I thought enum type can protect function parameters from out of bound mistake, but I tried the enum definition and the compiler doesn't give any warning to the out of bound parameter input, so what's the way to do this in C then?
Cheng
hi,
I thought enum type can protect function parameters from out of bound mistake, but I tried the enum definition and the compiler doesn't give any warning to the out of bound parameter input, so what's the way to do this in C then?
Cheng
Using an enum avoids the problem of out of bound values as the compiler will only accept valid enum definitions. However, this does not stop your code from values that are out of bounds!
Could you please post an example of what you're trying to do, that should make it clearer to us all.
// Available channels (FSCTRL.FREQ = 357 + 5(k-11), k=11,12...26) enum CC2420_channel { CHANNEL_11 = 0x0165, CHANNEL_12 = 0x016A, CHANNEL_13 = 0x016F, CHANNEL_14 = 0x0174, CHANNEL_15 = 0x0179, CHANNEL_16 = 0x017E, CHANNEL_17 = 0x0183, CHANNEL_18 = 0x0188, CHANNEL_19 = 0x018D, CHANNEL_20 = 0x0192, CHANNEL_21 = 0x0197, CHANNEL_22 = 0x019C, CHANNEL_23 = 0x01A1, CHANNEL_24 = 0x01A6, CHANNEL_25 = 0x01AB, CHANNEL_26 = 0x01B0, }; void CC2420_set_channel(enum CC2420_channel channel) { CC2420_SPI_STROBE(CC2420_SRFOFF); // enter IDLE mode first CC2420_SPI_SETREG(CC2420_FSCTRL, (0x4000 | channel)); CC2420_SPI_STROBE(CC2420_SRXON); // start Rx mode }
I thought this will provent user from using other values for the CC2420_channel, but when I tried to input other values, the C compiler still pass it without any warning
First, C lacks the kind of run-time system you can e.g. have with
Pascal where the run-time performs parameter checking. So if any
check can happen at all, it must be done at compile-time. You
write: ``The user...'' so I suspect you were expecting a run-time
check.
Second, in C, an enum is just an int which has symbolic names assigned
to it. It is assignment-compatible with type int, per definitionem.
The behaviour you are expecting is more what C++ actually implements,
where each enum forms its own namespace, and the compiler would really
reject assignments that are not made within that same namespace (unless
a type cast is applied, of course).
yes, what I want is this C++ like compile time bound checking. So is this anyway to do this in C then?