Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you assign a character value to a integer type variable in C?

Tags:

c

char

int

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?

like image 569
chanpkr Avatar asked Oct 24 '25 02:10

chanpkr


2 Answers

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.

like image 146
Keith Thompson Avatar answered Oct 25 '25 18:10

Keith Thompson


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.

like image 37
glglgl Avatar answered Oct 25 '25 17:10

glglgl