This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: warning on unsafe cast
- From: Eljay Love-Jensen <eljay at adobe dot com>
- To: Scott Lipcon <slipcon at mercea dot net>, gcc-help at gcc dot gnu dot org
- Date: Fri, 27 Feb 2004 08:53:36 -0600
- Subject: Re: warning on unsafe cast
- References: <20040227141039.70C58215@mercea.net>
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