user121615
user121615

Reputation: 199

Can you safely store char data in an int data type

I know that you can store integers up to like 100 and something in a char data type, but what about storing char data as in 'a' or 'b' in an int? I tried it and it seemed to work, but I'm not too sure if it's safe. Is it? Can I create an array of ints and use this array to store data in the form of 'x', 'b'...etc?

Upvotes: 2

Views: 228

Answers (2)

Potatoswatter
Potatoswatter

Reputation: 137780

Characters such as 'a' and 'b' simply represent integer values in the char data type. int is at least as wide as char, that is, it represents a superset of its values. So yes, perfectly safe.

Usually you will have sizeof(int) > sizeof(char), because the standard library wants to reserve one value for EOF (end-of-file). Technically, this luxury is optional, or at least unreliable, and you should use eofbit and such for compatibility with esoteric systems.

Upvotes: 1

SLaks
SLaks

Reputation: 887365

Yes; char is guaranteed to be smaller than int.

Upvotes: 1

Related Questions