Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++98 curly brace const scalar initialization

Tags:

c++

gcc

clang

c++98

I stumbled upon the code which I do not understand. Here's a simplified version of it:

template <int> struct A {};

int const i = { 42 };
typedef A<i> Ai;

int const j = 42;
typedef A<j> Aj;

This code compiles with GCC in C++98 mode, but not in Clang. Clang produces the following error:

$ clang -Wall -Wextra -std=c++98 -c test.cpp

test.cpp:4:11: error: non-type template argument of type 'int' is not an integral constant expression
typedef A<i> Ai;
          ^
test.cpp:4:11: note: initializer of 'i' is not a constant expression
test.cpp:3:11: note: declared here
int const i = { 42 };
          ^

As far as I understand initialization of int with and without curly braces should be equivalent. Clang initializes i correctly to 42, just doesn't think it's a compile time constant.

This code compiles well in C++11 mode.

Is there a reason j is treated as a compile time constant and i is not? Or is it simply a bug in Clang?

Update: I opened a ticket in LLVM bug tracker with this issue.

like image 732
detunized Avatar asked Dec 18 '13 16:12

detunized


People also ask

How do you write curly braces in C?

In programming, curly braces (the { and } characters) are used in a variety of ways. In C/C++, they are used to signify the start and end of a series of statements. In the following expression, everything between the { and } are executed if the variable mouseDOWNinText is true.

What do curly braces do in C++?

Different programming languages have various ways to delineate the start and end points of a programming structure, such as a loop, method or conditional statement. For example, Java and C++ are often referred to as curly brace languages because curly braces are used to define the start and end of a code block.

Does C++ need curly braces?

Curly braces (also referred to as just "braces" or as "curly brackets") are a major part of the C++ programming language. They are used in several different constructs, outlined below, and this can sometimes be confusing for beginners. An opening curly brace { must always be followed by a closing curly brace } .

Does C# use curly braces?

C# uses curly braces to indicate the start and end of a block of code. F# generally just uses indentation. Curly braces are used in F#, but not for blocks of code.


1 Answers

Yes, both declarations are equivalent, per C++98 8.5/13:

If T is a scalar type, then a declaration of the form

T x = { a };

is equivalent to

T x = a;

So both variables are constant, and initialised from a constant expression, so (as far as I can see) should both be usable as constant expressions.

like image 134
Mike Seymour Avatar answered Sep 25 '22 02:09

Mike Seymour