Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Assigning multiple characters in an int in C language
The character type data is stored by its ASCII value internally in C. If we want to print a single character as integer, we will get the ASCII value. But when we are trying to print more than one character using a single quote, then it will print some strange output.
Syntax
int variable = 'character'; int variable = 'multiple_chars'; // Non-standard behavior
Example
Please check the following program to get the idea −
#include <stdio.h>
int main() {
printf("%d
", 'A');
printf("%d
", 'AA');
printf("%d
", 'ABC');
return 0;
}
Output
65 16705 4276803
How It Works
The ASCII of A is 65. So at first it is showing 65 (binary: 01000001). Now for AA, it is showing 16705. This is formed by packing two ASCII values together:
-
'A'= 65 (0x41) -
'AA'= 0x4141 = 16705 in decimal -
'ABC'= 0x414243 = 4276803 in decimal
Each character is stored as one byte, and multiple characters are packed into the integer using little-endian or big-endian byte order depending on the system architecture.
Key Points
- Using multiple characters in single quotes is non-standard behavior and should be avoided.
- The result depends on the compiler and system architecture.
- For multiple characters, use string literals with double quotes instead.
Conclusion
While C allows multiple characters in single quotes, this creates implementation-defined behavior. It's better to use proper string handling with double quotes for multiple characters to ensure portability and clarity.
