Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a sequence point between structure member initializations?

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;
}
like image 788
Jon Hess Avatar asked Nov 05 '11 07:11

Jon Hess


People also ask

What is a sequence structure?

A sequence structure contains one or more subdiagrams, or frames, that execute in sequential order. Within each frame of a sequence structure, as in the rest of the block diagram, data dependency determines the execution order of nodes. There are two types of sequence structures—the Flat Sequence structure and the Stacked Sequence structure.

How to initialize structure members to default value in C?

However, C doesn't support any programming construct for default structure initialization. You manually need to initialize all fields to 0 or NULL. Initializing all fields to NULL is bit cumbersome process. Let's do a small hack to initialize structure members to default value, on every structure variable declaration.

What is the frame label in a stacked sequence?

The frame label in a Stacked Sequence structure is similar to the case selector label of the Case structure. The frame label contains the frame number in the center and decrement and increment arrows on each side. You cannot enter values in the frame label.

What are sequence points in C programming?

Between consecutive "sequence points" an object's value can be modified only once by an expression. The C language defines the following sequence points: Left operand of the logical-AND operator ( && ). The left operand of the logical-AND operator is completely evaluated and all side effects complete before continuing.


1 Answers

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.

like image 141
cnicutar Avatar answered Nov 09 '22 22:11

cnicutar