我听说C11添加了泛型.我已经google了一下,看了一些文章,了解到有一个新的关键字(_Generic)和所有.但我似乎无法把握住这一切.
它是类似C#中的泛型还是C++中的模板?任何人都可以简单解释一下C11的泛型定义,它的语法和一个简单的示例用法示例吗?
include/linux/typecheck.hLinux内核4.16 的文件包含此代码.
#define typecheck(type,x) \
({ type __dummy; \
typeof(x) __dummy2; \
(void)(&__dummy == &__dummy2); \
1; \
}
Run Code Online (Sandbox Code Playgroud)
检查if x是否与参数的类型相同type.
但我无法理解这一行:
(void)(&__dummy == &__dummy2);
Run Code Online (Sandbox Code Playgroud)
如何比较两个变量的第一个地址有帮助吗?
我想创建一个函数,该函数将采用可变数量的不同类型的参数。我的问题是如何解析参数类型。就像调用者可以以任何顺序传递任何类型的参数(不指定格式说明符)。所以在调用函数中我如何区分类型。
如何打印函数 var_argument 中调用者传递的所有值?
假设我想在调用者传递的参数的 var_argument 函数中执行 sprintf
这是我的 C 代码
#include <stdio.h>
#include <stdarg.h>
void var_argument(int num,...);
int main()
{
var_argument(3,"Hello",7.87f,6);
var_argument(3,7.87f,"Hello",6);
return 0;
}
void var_argument(int num,...)
{
char str[80];
/* What code should I write to differentiate between types and to print all the values passed by the caller */
va_list list;
va_start(list,num);
/* How to do sprintf of the parameter passed to this function and store
the formatted output in the array str */
}
Run Code Online (Sandbox Code Playgroud) 我如何断言 C 中的两种类型相等?在 C++ 中,我会使用 std::is_same,但搜索 StackOverflow 和其他地方似乎只能给出 C++ 和 C# 的结果。有没有办法在 C 中做到这一点?
请注意,这不是询问变量是否具有某种类型,而是询问两种类型是否相同。
我正在开发一种名为 BPML 的自定义编程语言,我想尝试更新名为 的输出函数say()。
C 中的最新版本:
void say(char *text) {
printf("%s", text);
}
Run Code Online (Sandbox Code Playgroud)
Python 的最新版本:
def say(text):
print(text, end = '')
Run Code Online (Sandbox Code Playgroud)
在 C 中,我希望它像 Python 的print()函数一样,只需在函数中输入变量即可,但在 C 中情况并非如此,因为您仍然必须使用适当类型的变量。
这就是为什么我在编写的程序中出现错误:
#include <stdio.h>
void say(char *text);
int main() {
int number = 21;
say(number);
}
void say(char *text) {
// Output function
}
Run Code Online (Sandbox Code Playgroud)
错误:
P1.c:7:9: error: incompatible integer to pointer conversion passing 'int' to parameter of type 'char *' [-Werror,-Wint-conversion]
say(number);
^~~~~~
Run Code Online (Sandbox Code Playgroud)
我仍然需要使用itoa()中的函数<stdlib.h>,但我没有想到,因为它在 CI …
如何检查我的结构something在 C99 中是否有成员?
#include <stdlib.h>
#include <string.h>
struct some {
char title[50];
char name[50];
};
int main() {
struct some s;
if (*s.something) { // Error: no member named 'something' in 'struct.some'
strcpy(s.something, "Hello");
}
}
Run Code Online (Sandbox Code Playgroud)
更新:
我不需要知道它在编译时是否存在,而是在构建的程序中。成员及其值将从文件中解析,然后在循环中消耗到结构中,但我需要确保它会跳过所有不存在的成员。