简体   繁体   中英

is using int variables as char variables OK?

so my question is why do some people use int variables as char variables. exemple

int main()

{

 int i;

 scanf("%c",&i);

printf ("%c",i);

}

thank's in advance

C's char is an integer type. Its (numeric) values are most often used to represent characters, but that's a separate matter.

You can safely use a variable of type int to hold a value in the range of type char . You can assign a char to an int or pass a char to a function expecting an int, both without a cast and without altering the value.

In certain places, int is used intentionally instead of char to represent characters. The canonical case is probably the standard library's getc() , fgetc() , and getchar() functions, which need the range of an int to be able to represent EOF in addition to every possible char value. Also, for historical reasons, some other functions declare int arguments to accept data expected to be of type char ; memset() is one of the better known of these.

On the other hand, pointers to int and to char are not interchangeable. As others pointed out, your scanf() call produces undefined behavior for that reason.

Generally speaking, you should use char rather than int to represent character data, unless there is a good, externally-driven reason to do otherwise (such as needing to handle the return value of getchar() ). Even more generally speaking, match data types correctly, being deliberate about where you allow type conversions to be performed.

This -

scanf("%c",&i);

Wrong argument is passed ( %c expects address of char ).It invokes undefined behaviour .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM