在C preprocessor ​​strlen的? [英] strlen in the C preprocessor?

查看:100
本文介绍了在C preprocessor ​​strlen的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能实施的strlen() C preprocessor?

假设:

 的#define MyString的鲍勃

有一些preprocessor宏, X ,这将让我说:

 的#define MYSTRING_LEN X(MyString的)


解决方案

它不使用preprocessor,但sizeof运算在编译时得到解决。如果字符串是一个数组,你可以用它来确定在编译时其长度:

 静态常量字符字符串[] =鲍勃;
的#define STRLEN(多个)(sizeof的(多个)/的sizeof(S [0]))

请即 STRLEN 上面将包括空终止,不像 strlen的事实()

Is it possible to implement strlen() in the C preprocessor?

Given:

#define MYSTRING "bob"

Is there some preprocessor macro, X, which would let me say:

#define MYSTRING_LEN X(MYSTRING)

解决方案

It doesn't use the preprocessor, but sizeof is resolved at compile time. If your string is in an array, you can use that to determine its length at compile time:

static const char string[] = "bob";
#define STRLEN(s) (sizeof(s)/sizeof(s[0]))

Keep in mind the fact that STRLEN above will include the null terminator, unlike strlen().

这篇关于在C preprocessor ​​strlen的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆