英文:
What to do to make '_Generic('a', char : 1, int : 2) == 1' true
问题
编译器是否可以将类型'a'设置为char,而不是int?这会使这些表达式的值为真:
sizeof('a') == 1
_Generic('a', char : true, default : false)
在gcc中,_Generic('a', char : true, default : false) == false。
英文:
Is there any way the compiler can set the type 'a' to char, instead of int.
This makes the values of these expressions true:
sizeof('a') == 1
_Generic('a', char : true, default : false)
In gcc _Generic('a', char : true, default : false) == false
答案1
得分: 1
问题是,C 中的字符常量是 int 而不是 char。这是C语言的一个众所周知的缺陷。解决这个问题的一个简单方法是将特定文件编译为C++,然后将生成的 .o 文件与C项目的其余部分链接起来。
否则,您将不得不通过某些神秘的宏来发明自己的自定义表示法,这真的是不推荐的。例如:
#include <stdio.h>
#define CH(c) (#c [0])
int main(void)
{
printf("%c %zu\n", CH(a), sizeof(CH(a)));
}
类似地,"a"[0] 或 *"a" 将输出类型为 char 大小为 1 的字母 a。
这仍然允许十六进制转义序列等操作,例如 CH(\x61) 可以打印出 a。
英文:
The problem is that character constants in C are int, not char. This is a well-known flaw of the C language. One easy solution to the problem might be to compile a specific file as C++, then link the generated .o file with the rest of the C project.
Otherwise you'd have to invent your own custom notation through some mysterious macro, which is really NOT recommended. For example:
#include <stdio.h>
#define CH(c) (#c [0])
int main (void)
{
printf("%c %zu\n", CH(a), sizeof(CH(a)) );
}
Similarly, "a"[0] or *"a" will give the letter a of type char with size 1.
This will still allow hex escape sequences and the like, such as CH(\x61) to print a.
答案2
得分: 0
你可以使用(char)'a'来代替a。
sizeof((char)'a') // 1
_Generic((char)'a', char: true, default: false) // true
英文:
You can use (char)'a' instead of a.
sizeof( (char)'a' ) // 1
_Generic( (char)'a', char : true, default : false ) // true
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论