Can character be classified as an integer in C language.
I am talking in context of a lexical analyzer.I am building a scanner using C language.
Can character be classified as an integer in C language.
I am talking in context of a lexical analyzer.I am building a scanner using C language.
You can simply do:
const char str[] = "Hello world";
char c = 'H';
// And use any of these:
int chr = 'H'; // chr = 0x48
chr = c; // chr = 0x48
chr = str[0]; // chr = 0x48
And you'll always end up having 0x48
(72) in chr
.
Perhaps you want to ask if char can be classified as numbers
. If so, yes they can, as char variables stores the value of a char as a number.
Say:
char c = 120; //legal
The range of the numbers you can store in a char depends on the compiler. Most commonly, char variables stores values of a range from -128
to 127
, total 256 possibilities.
As per Variables. Data Types. - C++ Documentation
You can also work with unsigned chars, that goes from 0
to 255
.
Please realize that if you store a number out of this range you will lose precision. Say:
char c = 300;
int i = c;
std::cout << i; //prints 44
system("pause");
return 0;
In "The C Programming Language" (second edition) it is specifically mentioned that there is no distinction between char and int types as far as character manipulation functions of stdio.h are concerned.
The type char is specifically meant for storing (such) character data, but any integer type can be used
This is an example adapted from the book and illustrating this:
#include <stdio.h>
/* copy input to output */
int
main(void)
{
int c;
while ((c = getchar()) != EOF)
putchar(c);
}
Of course, charactor can be implicitly converted to an integer.
char a = 'c';
int b = a;
Using TypeCasting:
char c = 'a';
int x = (int) c;
printf("%d\n", c);
OR
char c = 'a';
printf("%d\n", c);
Both will give you 97
Characters are represented as integers. One common pitfall when analysibng input is shown below:
char c; // (!!) should be of type int to hold EOF
while((c = getchar()) != EOF) {
// ...
}
char
is an integer type like int
with a reduced range.
You can add, multiply, shift, print, scan as you would with int
, short
, long
or long long
. char
has a smaller range than the others. Much code involving char
and short
silently promote to int
, so care is needed.
char c;
int i;
c = -2; // OK
i = -2; // OK
// sizeof(c) == 1
// sizeof(i) >= 2 (often 4, sometimes 8)
scanf("%hhd", &c);
scanf("%d", &i);
printf("%hhd", c);
printf("%d", i);
On exotic machines where a byte
is > 9 bits, additional issues apply.