Initialisation

G

grid

Hi,
I have the following code that seems to fail :

#include<stdio.h>
char c = "hello"[0];
int main()
{
printf("c == [%c]\n",c);
return 0;
}

And the below snippet passes :
#include<stdio.h>
int main()
{
char c = "hello"[0];
printf("c == [%c]\n",c);
return 0;
}

From the standard :
All objects in static storage shall be initialized (set to their initial
values) before program startup. The manner and timing of such
initialization are otherwise unspecified.

But I can see in one compiler that it dosent even warn and compiles
cleanly though gcc cribs about it that "initializer element is not
constant".

Which behaviour seems to be correct ??

TIA
~
 
P

pete

grid said:
Hi,
I have the following code that seems to fail :

#include<stdio.h>
char c = "hello"[0];
int main()
{
printf("c == [%c]\n",c);
return 0;
}

And the below snippet passes :
#include<stdio.h>
int main()
{
char c = "hello"[0];
printf("c == [%c]\n",c);
return 0;
}

From the standard :
All objects in static storage shall be initialized
(set to their initial values)
before program startup. The manner and timing of such
initialization are otherwise unspecified.

But I can see in one compiler that it dosent even warn and compiles
cleanly though gcc cribs about it that "initializer element is not
constant".

Which behaviour seems to be correct ??

The externally defined object initialization
requires a constant expression and doesn't have one.
Violation of a "shall" constraint, gives undefined behavior.

N869
6.7.8 Initialization

[#4] All the expressions in an initializer for an object
that has static storage duration shall be constant
expressions or string literals.



6.6 Constant expressions

[#7] More latitude is permitted for constant expressions in
initializers. Such a constant expression shall be, or
evaluate to, one of the following:
-- an arithmetic constant expression,
-- a null pointer constant,
-- an address constant, or
-- an address constant for an object type plus or minus an
integer constant expression.

[#8] An arithmetic constant expression shall have arithmetic
type and shall only have operands that are integer
constants, floating constants, enumeration constants,
character constants, and sizeof expressions.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top