你如何用C声明字符串常量? [英] How do you declare string constants in C?

查看:368
本文介绍了你如何用C声明字符串常量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这是很地道的,或者至少是良好的作风,在C申报数字常量为枚举的S代替的#define ING他们。

I know it's quite idiomatic, or good style at least, in C to declare numeric constants as enums instead of #defineing them.

/* bad style */
#define MAXLINE 1024

/* good/better style */
enum {
    MAX_LINE = 1024
};

有没有字符串常量的定义?

Is there an equivalent rule for the definition of string constants?

/* is this good style? */
#define HELLO "Hello World"

/* or is this better? */
const char *HELLO2 = "Howdy";

你这是什么preFER?如果可能的话显示这两种方法的一些缺点。

What do you prefer? If possible show some drawbacks of either method.

推荐答案

还有一(至少)大路通罗马:

There's one more (at least) road to Rome:

static const char HELLO3[] = "Howdy";

静态 - 可选 - 是从与其他文件相冲突prevent它)。我倒是preFER这其中超过为const char * ,因为这样你就可以使用的sizeof(HELLO3),因此你不必推迟到运行时,你可以在编译的时候做什么。

(static — optional — is to prevent it from conflicting with other files). I'd prefer this one over const char*, because then you'll be able to use sizeof(HELLO3) and therefore you don't have to postpone till runtime what you can do at compile time.

该定义有编译时并置的一个优势,但是(认为 HELLO,世界!),你可以的sizeof(HELLO) 以及

The define has an advantage of compile-time concatenation, though (think HELLO ", World!") and you can sizeof(HELLO) as well.

不过,你也可以preFER 为const char * ,并用它在多个文件,这会节省你的内存一口。

But then you can also prefer const char* and use it across multiple files, which would save you a morsel of memory.

总之 - 这取决于

这篇关于你如何用C声明字符串常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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