Quantcast
Channel: C Pre-Processor Macro code with () and {} - Stack Overflow
Viewing all articles
Browse latest Browse all 4

Answer by Eric Postpischil for C Pre-Processor Macro code with () and {}

$
0
0

For c, the initializer is an expression, and its value is 3. For d, the initializer is a list in braces, and it provides too many values, of which only the first is used.

After macro expansion, the definitions of c and d are:

unsigned int c = (1,2,3);unsigned int d = {1,2,3};

In the C grammar, the initializer that appears after unsigned int c = or unsigned int d = may be either an assignment-expression or {initializer-list} (and may have a final comma in that list). (This comes from C 2018 6.7.9 1.)

In the first line, (1,2,3) is an assignment-expression. In particular, it is a primary-expression of the form (expression). In that, the expression uses the comma operator; it has the form expression,assignment-expression. I will omit the continued expansion of the grammar. Suffice it to say that 1,2,3 is an expression built with comma operators, and the value of the comma operator is simply its right-hand operand. So the value of 1,2 is 2, and the value of 1,2,3 is 3. And the value of the parentheses expression is the value of the expression inside it, so the value of (1,2,3) is 3. Therefore, c is initialized to 3.

In contrast, in the second line, {1,2,3} is {initializer-list}. According to the text in C clause 6.7.9, the initializer-list provides values used to initialize the object being defined. The {} form is provided to initialize arrays and structures, but it can be used to initialize scalar objects too. If we wrote unsigned int d = {1};, this would initialize d to 1.

However, 6.7.9 2 is a constraint that says “No initializer shall attempt to provide a value for an object not contained within the entity being initialized.” This means you may not provide more initial values than there are things to be initialized. Therefore, unsigned int d = {1,2,3}; violates the constraint. A compiler is required to produce a diagnostic message. Additionally, your compiler seems to have gone on and used only the first value in the list to initialize d. The others were superfluous and were ignored.

(Additionally, 6.7.9 11 says “The initializer for a scalar shall be a single expression, optionally enclosed in braces.”)


Viewing all articles
Browse latest Browse all 4

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>