开发者

Define integer ranges in C

I want to define a type named Int_1_100_Type which is an integer variable in the range from 1 to 100. How should I define this one?

for example: I am passing this variable 开发者_运维技巧to a function which accepts variable of type Int_1_100_Type, funca(Int_1_100_Type Var1)


You can't, C has no such functionality. You can of course typedef an int:

typedef int int_1_100_Type;

but there is no way of restricting its range. In C++, you could create a new type with this functionality, but I think very few people would bother - you just need to put range checks in the function(s) that use the type.


Of course you can. All you need is a little object-based C.

create a file with a struct and some members

typedef struct s_foo {
  int member;
} Foo;

Foo* newFoo(int input);   // ctor
void get(Foo *f);         // accessor

Enforce your condition in the mutator/ctor

If you do this in its own file, you can hide the impl of the class as well, you can do oo-like C


You can't put that kind of limit on the range of an integer.

You can of course typedef it anyway:

typedef int int_1_100;

or even better:

typedef unsigned int int_1_100;

But nothing in C will prevent you from writing:

int_1_100 x = 1000;

To implement something like that, you need to hide the implementation, but that will make it harder to initialize the value (and impossible to allocate values of the type on the stack, with the hiding intact).


There's no way in c to define a type that must be in a specific range. You could however check each value in your functions, e.g.

int funca(int Var1)
{
    assert(Var1 >= 1);
    assert(Var1 < 101);
    ...
}


In C++, there would be a way to do this by writing a class that would act like an integer, but it would be way too much effort and way too heavyweight a solution to be practical.

Thanks Naveen for pointing out the question was C only.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜