-
using const
Why won't this usage of const work? If I compile it as c++ is works. I'm using Borland C++ 4.5.
Code:
#include <stdio.h>
#include <conio.h>
const char K_ESC = 0x1B;
int main()
{
char c;
c = getch();
switch(c)
{ case K_ESC : printf("You have escaped!");
break;
}
getch();
}
-
Code:
const char K_ESC = '0x1B'; /*note quotes*/
not sure of 0x1B for escape key try '\x1b'
-
Code:
#define K_ESC '\1B'
By the way. Even a const char is a variable, although it may not be altered. The cases in the switch structure do really need real constants.
-
have modified your program slightly
Code:
#include <stdio.h>
#include <conio.h>
#define K_ESC '\x1B'
int main()
{
char c;
c = getch();
if(c == K_ESC)
printf("You have escaped!");
else
printf("You didnot hit Esc");
getch();
return 0;
}
-
const has different meanings in C and C++
In C
const char K_ESC = 0x1B;
All this means is that K_ESC should not be changed, and that the compiler should warn you if you try and do something like K_ESC++;
The case statement requires
case constant-expression (eg. 2 + 3 - 4 )
but in your context, you have
case identifier
and the compiler can't look inside that identifier at compile time to get the const value.
In C++
const char K_ESC = 0x1B;
This really is a constant, and is somewhat akin to
#define K_ESC 0x1B
but with all the advantages of type checking.