Print decimal value of a char
打印字符十进制值的程序:
1 2 3 4 5 6 7 8 9 |
为什么打印第二个字符的十进制值,为什么不是第一个字符的十进制值?
输出:
因为
通常,您只在单引号中间使用单个字符。如果使用多个字符,
如果你使用过 gcc,那么根据这个来源会发生这种情况
The compiler evaluates a multi-character character constant a character at a time, shifting the previous value left by the number of bits per target character, and then or-ing in the bit-pattern of the new character truncated to the width of a target character. The final bit-pattern is given type int, and is therefore signed, regardless of whether single characters are signed or not. If there are more characters in the constant than would fit in the target int the compiler issues a warning, and the excess leading characters are ignored.
For example,
'ab' for a target with an 8-bit char would be interpreted as a€?(int) ((unsigned char) 'a' * 256 + (unsigned char) 'b') a€?, and'\\234a' as a€?(int) ((unsigned char) '\\234' * 256 + (unsigned char) 'a') a€?
1 2 3 |
Why it is printing the decimal value of second character,why not the first character's decimal value?
The value of an integer character constant containing more than one character (e.g., 'ab'), or containing a character or escape sequence that does not map to a single-byte execution character, is implementation-defined. C11 ?§6.4.4.4 10
示例:您的输出可能不同。
1 2 |
16706 与 0x4142 的值相同,0x4142 是 ASCII
将
`
1 2 |
将
1 2 3 4 | // Example warning // warning: overflow in implicit constant conversion [-Woverflow] char ch1 = 'AB'; char ch2 = 16706; |
此外,鉴于此类辅音的实现定义性质,以下内容也可能会发出警告:
1 2 3 | // Example warning // warning: multi-character character constant [-Wmultichar] char ch1 = 'AB'; |
多字符字符常量的使用仅限于少数选择情况。如此之少,它更有可能是一个很好用的编码错误。
C11 $6.4.4.4(字符常量):
A multi-char always resolves to an int, but that the exact value is
a€?implementation-dependenta€?. That is, different compilers may resolve
the same multi-char to different integers. This is a portability
problem, and it is one of the reasons multi-chars are discouraged.
表示
所以用
1 | char ch = 'A'; |
而不是
1 | char ch = 'AB'; |
并为
1 2 |
伊哈罗布是对的。
", ab[0]);
首先,这个程序会抛出一个类似
的警告
1 2 3 | 4:12: warning: multi-character character constant [-Wmultichar] In function 'int main()': 4:12: warning: overflow in implicit constant conversion [-Woverflow] |
如果您了解运算符优先级的概念,将帮助您了解为什么要获取第二个字符 (B) 的十进制值。在赋值运算符中,优先级从右到左开始。所以在这种情况下,最右边的字符具有更高的优先级并存储到 char ch 中,其余字符被忽略。
输出:
1 2 | ch is 66 ch1 is 'G' |
另一个使用赋值运算符的例子:
1 2 3 4 5 6 7 8 9 | #include<stdio.h> int main(void){ int a = (2,3,4,5,6); // Here 6 is assigned to 'a' and remaining values are ignored. printf("a is %d\ ",a); } |
输出:
1 | a is 6 |
请通过以下链接了解运算符优先级。
http://en.cppreference.com/w/c/language/operator_precedence