Reputation: 134
I tried to define a 'natural' type, like that:
typedef unsigned int nat;
But if I define a nat variable, that variable behaves like an ordinary int:
nat natural_index;
natural_index = 10; // That's what I want.
natural_index = -10; // Still a valid option.
In resume, I wanted to know why the compiler does not show a message, like "-10 is not a unsigned int", and what could I do to define a 'natural' type.
extra information: I "printf" the variable natural_index, and the value '-10' was printed. I expected at least, another positive number (not exactly 10).
Upvotes: 0
Views: 435
Reputation: 140569
C doesn't support what you are trying to do, on two different levels.
First, a typedef
in C does not create a new, distinct type; it just creates a shorthand name for the original type. Thus, after
typedef unsigned int nat;
the declaration
nat natural_index;
is 100% equivalent to
unsigned int natural_index;
(What's the point of typedef
, then? It's most useful when the "underlying type" might differ based on the target architecture; for instance, the standard typedef uint64_t
might be shorthand for unsigned long
or unsigned long long
depending on the architecture.)
Second, C has no mechanism for changing whether or not arithmetic expressions perform implicit conversions. In
natural_index = -10;
the assignment operator will convert the negative number -10
(with type int
) to a large unsigned number (namely (UINT_MAX - 10) + 1
, which is probably, but not necessarily, 4,294,967,286) in the process, and there is no way to disable that.
Your options are to work in a language that actually supports this kind of thing (e.g. Ada, Haskell, ML) or to write a "linting" program that parses C itself and enforces whatever rules you want it to enforce (existing examples are lint
and sparse
).
Upvotes: 5
Reputation: 15793
you forgot to separate the expression-statements with semicolon ;
.
natural_index = 10;
natural_index = -10;
-10
to a large signed number during the evaluation of assignment operator =
.
6.5.16.1p2
(Simple assignment) from ISO9899 says:
In simple assignment (=), the value of the right operand is converted to the type of the assignment expression.
When you use the storage class specifier typedef
, this tells the parser to add an alias identifier nat
for the type unsigned int
in the environment of the parser or in the parse tree that it outputs. In this case nat
will be evaluated to a type in declarations, so when you declare the object with identifier natural_index
, the left-value associated with this object will have the type unsigned int
.
Upvotes: 2