Bug 71983 - "error: initializer element is not constant" only with -O0
Summary: "error: initializer element is not constant" only with -O0
Status: RESOLVED FIXED
Alias: None
Product: gcc
Classification: Unclassified
Component: c (show other bugs)
Version: 6.1.0
: P3 normal
Target Milestone: ---
Assignee: Not yet assigned to anyone
URL:
Keywords: rejects-valid
Depends on:
Blocks:
 
Reported: 2016-07-23 17:32 UTC by Karlson2k
Modified: 2021-09-27 20:44 UTC (History)
1 user (show)

See Also:
Host:
Target:
Build:
Known to work: 8.1.0
Known to fail: 5.2.1, 7.5.0
Last reconfirmed: 2016-07-23 00:00:00


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description Karlson2k 2016-07-23 17:32:00 UTC
Got error "error: initializer element is not constant" when following code is compiled with '-O0'

int main(void)
{
  static const int a = 1;
  static const int b = 2;
  static const int c = a + b;

  return c;
}

If same code is compiled with -O1, -O2, -O3, -Ofast or even -Og, no errors and no warnings are generated.
Comment 1 Andrew Pinski 2016-07-23 17:35:32 UTC
This is not valid C code.  Now GCC should be consistent at different optimization levels.
Comment 2 Karlson2k 2016-07-23 17:38:49 UTC
clang and MSVC accept this code.
Inconsistency at different optimization levels is confusing and make harder to reveal errors in code.
Comment 3 Martin Sebor 2016-07-23 19:27:30 UTC
I'll confirm this bug report based on comment #1, and also in light of enhancement requests to have GCC treat more expressions as constant (e.g, bug 69960 and bug 71713).  It would make sense treat this one as a constant expression as well.  Other C implementations like Clang have done so.
Comment 4 Richard Biener 2021-06-18 06:14:19 UTC
Fixed in GCC 8+