Reputation: 915
In C,
...
int num = 'a';
...
My question is simple. How can you assign a character such as '0', 'a', 'b' to an integer type variable without getting any type error in C language?
Upvotes: 4
Views: 17825
Reputation: 672
(sorry I read the question wrong and wrote a comment, my bad) ----->
int main()
{
int num = 'a';
printf("%c", num);
return 0;
}
OUTPUT
a
Upvotes: 0
Reputation: 263237
For historical reasons (mostly), character constants are of type int
in C.
But even if they weren't, an initialization like
int num = 'a';
or an assignment like
num = 'a';
would still be perfectly legal. A value of any numeric type may be assigned to a variable of any (other) numeric type, and the value will be implicitly converted (which may involve a change of representation and/or a risk of overflow).
And char
, along with its relatives unsigned char
and signed char
, are numeric types, specifically integer types.
Upvotes: 4
Reputation: 8946
Take a look here and here. Every character is a number, actually everything in computing is numbers, just some of them (depending on type and value) are rendered like characters.
For storing characters variable type should be char
or wchar_t
but it can be any other type, because all of them are just a numbers in memory.
Upvotes: 0
Reputation: 5163
You can. In C character constant is of type int
. Which makes it a bit different with C++.
Upvotes: 0
Reputation: 91017
The character is only a representation of an integer value. For example, '0'
can be written as 0x30
or 48
, 'a'
is an alternative for 0x61
or 97
, etc.
So the assignment is perfectly valid.
Upvotes: 4