Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is top-level in C++?

In example 14 under [dcl.init.list], the standard uses the term "top-level" when describing the semantics of code using list-initialization, in the context of narrowing conversions. I don't know what this means.

This code executes without errors:

int f(int a) { return 1;}

int main() {
    int a[] = {f(2), f(2.0)};  
    int b[] = {f(2.0), f(2)}; // No error because: double-to-int conversion is not at the top-level
}

I also tried the following. I figured it is nothing to do with the order of initialization:

int f(int a) { return 1;}

int main() {
    int a[] = {f(2), f(2.0)};  
    int b[] = {f(2.0), f(2)}; // double-to-int conversion is not at the top-level
    //int c[] = {f(2147483645.0f), f(2)}; // This is erroring out due to narrowing.
    int d[] = {f(2), f(2.0)};  // Now I'm sure top-level doesn't mean the order of initialization. 
}

I want to know what is a top-level? The documentations here and here do not describe it.

The reason I'm curious about this term is because I'm trying to understand when would list-initializers work when narrowing conversion is implicitly invoked.

I'm also not sure about the terminology. For example, is there something like a top-level class, or a top-level type, or a top-level list-initializer?

like image 916
Jerry Ajay Avatar asked Nov 11 '20 18:11

Jerry Ajay


1 Answers

This is not a strictly defined term. But in [dcl.init.list]/note-7 that you linked, "at the top level" seems to mean "written directly in a braced list, rather than in a nested expression".

So, in int x[] = {1.0, f(2.0)};, 1.0 is at the top level, because it's written directly in the braced list, but 2.0 is not because it's nested in a function-call expression.

like image 96
HolyBlackCat Avatar answered Sep 29 '22 05:09

HolyBlackCat