我怎样才能在C中有一个变量,其值应该只在20到520之间?我想将变量赋值限制在20到520之间的值?如果我取一个值从20开始的枚举,我仍然需要在枚举中定义另外519个值.
小智 9
C没有办法直接表达你想要的东西.请注意,即使是enum不强制执行有效值.您可以指定任何基础类型的值enum.
您总是可以提出自己的逻辑,例如,如果这是您作为结构建模的对象的一部分:
struct foo
{
unsigned bar;
};
// [...]
int foo_setBar(struct foo *self, unsigned val)
{
if (val < 20 || val > 520) return -1;
self->bar = val;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能在C中有一个变量,其值应该只在20到520之间?
C中没有这样的数据类型.
即使范围接近某些类型的极限,下溢或溢出的危险仍然是一件事(unsigned int例如,想象一下,你希望下限为0,但有人可能超出界限).
你可以做的是编写自己的结构,访问器和/或枚举来实现这一点.如果您有兴趣,请阅读Paul R的回答.但是我不鼓励你这样做.
我会这样做,例如,如果变量是由用户填写的:
int v;
do {
scanf("%d", &v);
} while(!(v >= 20 && v <= 520));
Run Code Online (Sandbox Code Playgroud)
以便一次又一次地提示用户,直到他的输入符合标准.
PS:这听起来像一个XY问题.
不幸的是,C不提供对struct成员的访问控制.一开始运气不好.
您必须(尝试?)以任何合适的方式解决此限制.人们可能会隐藏用户的数据:
type.h:
#include <stdbool.h>
struct TheType;
typedef struct TheType TheType;
unsigned short get(TheType const* type);
bool set(TheType* type, unsigned short value);
Run Code Online (Sandbox Code Playgroud)
type.c:
struct TheType
{
unsigned short value;
}
unsigned short get(TheType const* type)
{
return type->value;
}
bool set(TheType* type, unsigned short value)
{
if(value < 20 || value > 520)
return false;
type->value = value;
return true;
}
Run Code Online (Sandbox Code Playgroud)
然而,这带来了另一个缺点,因为其他功能sizeof也会变得无法使用......我们可能必须提供至少一个size_t sizeofTheType()允许用户分配适当内存量和其他东西的功能.
好吧,你可以:
typedef enum {
F_FIRST = 20,
E_LAST = 520
} MySpecialEnum;
Run Code Online (Sandbox Code Playgroud)
但是,无论是在编译时还是在运行时,都不会强制执行此范围,但您可以使用它进行显式范围检查,并作为自记录代码的辅助。
typedef enum {
F_FIRST = 20,
E_LAST = 520
} MySpecialEnum;
Run Code Online (Sandbox Code Playgroud)
然后您可以在运行时进行范围检查,而无需任何显式代码。当然,这会带来性能损失。