Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
497 views
in Technique[技术] by (71.8m points)

c - Difference between char and int when declaring character

I just started learning C and am rather confused over declaring characters using int and char.

I am well aware that any characters are made up of integers in the sense that the "integers" of characters are the characters' respective ASCII decimals.

That said, I learned that it's perfectly possible to declare a character using int without using the ASCII decimals. Eg. declaring variable test as a character 'X' can be written as:

char test = 'X';

and

int test = 'X';

And for both declaration of character, the conversion characters are %c (even though test is defined as int).

Therefore, my question is/are the difference(s) between declaring character variables using char and int and when to use int to declare a character variable?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The difference is the size in byte of the variable, and from there the different values the variable can hold.

A char is required to accept all values between 0 and 127 (included). So in common environments it occupies exactly one byte (8 bits). It is unspecified by the standard whether it is signed (-128 - 127) or unsigned (0 - 255).

An int is required to be at least a 16 bits signed word, and to accept all values between -32767 and 32767. That means that an int can accept all values from a char, be the latter signed or unsigned.

If you want to store only characters in a variable, you should declare it as char. Using an int would just waste memory, and could mislead a future reader. One common exception to that rule is when you want to process a wider value for special conditions. For example the function fgetc from the standard library is declared as returning int:

int fgetc(FILE *fd);

because the special value EOF (for End Of File) is defined as the int value -1 (all bits to one in a 2-complement system) that means more than the size of a char. That way no char (only 8 bits on a common system) can be equal to the EOF constant. If the function was declared to return a simple char, nothing could distinguish the EOF value from the (valid) char 0xFF.

That's the reason why the following code is bad and should never be used:

char c;    // a terrible memory saving...
...
while ((c = fgetc(stdin)) != EOF) {   // NEVER WRITE THAT!!!
    ...
}

Inside the loop, a char would be enough, but for the test not to succeed when reading character 0xFF, the variable needs to be an int.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...