结构体成员初始化之间是否存在序列点?

发布于 2024-12-13 13:53:13 字数 594 浏览 0 评论 0原文

结构成员初始化表达式之间是否存在序列点?

例如,下面的代码是否总是打印“a,b”?

#include <stdio.h>

typedef struct {
    char *bytes;
    int position;
    int length;
} Stream;

typedef struct {
    char a;
    char b;
} Pair;

char streamgetc(Stream *stream) {
    return (stream->position < stream->length) ? stream->bytes[stream->position++] : 0;
}

int main(void) {
    Stream stream = {.bytes = "abc", .position = 0, .length = 3};
    Pair pair = {.a = streamgetc(&stream), .b = streamgetc(&stream)};
    printf("%c, %c\n", pair.a, pair.b);
    return 0;
}

Is there a sequence point between structure member initialization expressions?

For example, is it well defined that the code bellow will always print "a, b"?

#include <stdio.h>

typedef struct {
    char *bytes;
    int position;
    int length;
} Stream;

typedef struct {
    char a;
    char b;
} Pair;

char streamgetc(Stream *stream) {
    return (stream->position < stream->length) ? stream->bytes[stream->position++] : 0;
}

int main(void) {
    Stream stream = {.bytes = "abc", .position = 0, .length = 3};
    Pair pair = {.a = streamgetc(&stream), .b = streamgetc(&stream)};
    printf("%c, %c\n", pair.a, pair.b);
    return 0;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

找个人就嫁了吧 2024-12-20 13:53:13

我认为 §6.7.8-23 解决了这个问题:

初始化列表中任何副作用发生的顺序
表达式未指定。

关于复合文字:

<代码>§6.5.2.5-7

6.7.8 中初始化列表的所有语义规则和约束
适用于复合文字。

I think §6.7.8-23 settles it:

The order in which any side effects occur among the initialization list
expressions is unspecified.

And about compound literals:

§6.5.2.5-7

All the semantic rules and constraints for initializer lists in 6.7.8
are applicable to compound literals.

北恋 2024-12-20 13:53:13

我相信C99 TC2(n1124)中的相关措辞位于§6.7.8/23中:

初始化列表表达式中任何副作用发生的顺序是
未指定131

脚注说:

131) 特别是,求值顺序不必与子对象初始化的顺序相同。

I believe the relevant wording in C99 TC2 (n1124) is in §6.7.8/23:

The order in which any side effects occur among the initialization list expressions is
unspecified131.

The footnote says:

131) In particular, the evaluation order need not be the same as the order of subobject initialization.

陌上青苔 2024-12-20 13:53:13

不会。您可以在 C 标准的附录 C(或草案 n1256、n1516 等)中亲自查看。

每个完整声明符后面都有一个序列点,并且在初始化内部使用&&或调用函数的表达式中仍然存在序列点。

函数参数之间也没有序列点。

func(getc(), getc()); // who knows what order?

No. You can see for yourself in Annex C of the C standard (or drafts n1256, n1516, etc.).

There is a sequence point after each full declarator, and there will still be sequence points from expressions inside the initialization that use && or call functions.

There isn't a sequence point between function arguments either.

func(getc(), getc()); // who knows what order?
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文