This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: warning on unsafe cast


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


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]