warning on unsafe cast
Eljay Love-Jensen
eljay@adobe.com
Fri Feb 27 15:24:00 GMT 2004
Hi Scott,
This will address your C issue:
#include <limits.h>
#include <stdio.h>
int main(int argc, char *argv[]) {
int i;
short s;
i = atoi(argv[1]);
assert(i >= SHRT_MIN);
assert(i <= SHRT_MAX);
s = i;
printf("%d\n", s);
return 0;
}
If you need this in many places:
#include <limits.h>
#include <stdio.h>
void ShortAssignInt(short* s, int i)
{
assert(i >= SHRT_MIN);
assert(i <= SHRT_MAX);
*s = i;
}
int main(int argc, char *argv[]) {
int i;
short s;
i = atoi(argv[1]);
ShortAssignInt(&s, i);
printf("%d\n", s);
return 0;
}
Another solution (more friendly in C++ than in C) is:
#include <stdio.h>
struct Short { short m; };
struct Int { int m; }
int main(int argc, char* argv[])
{
Int i;
Short s;
i.m = atoi(argv[1]);
s = i; // Error generated.
printf("%d\n", s.m);
return 0;
}
Another alternative would be to use Ada instead of C.
If you want a Lint tool, I've had good luck with Gimpel's PC-lint or
FlexeLint. (http://www.gimpel.com/).
HTH,
--Eljay
More information about the Gcc-help
mailing list