Why does the compiler reject a constant default parameter value with “E2026 Constant expression expected”?

后端 未结 1 1638
情书的邮戳
情书的邮戳 2021-01-20 18:01

The following code fails to compile with [dcc32 Error] TestDefaultParameterValuePrj.dpr(13): E2026 Constant expression expected:

program TestDefaultParameter         


        
相关标签:
1条回答
  • 2021-01-20 18:36

    From the documentation, with my emphasis:

    You can specify default parameter values in a procedure or function heading. Default values are allowed only for typed const and value parameters. To provide a default value, end the parameter declaration with the = symbol followed by a constant expression that is assignment-compatible with the parameter's type.

    A typed constant is not a constant expression. Declare your constant as a true constant which is a constant expressioin:

    const
      SomeValue = 'T';
    

    The somewhat thorny issue of true constants, typed constants and constant expressions is covered here: Declared Constants. Some key excerpts:

    A constant expression is an expression that the compiler can evaluate without executing the program in which it occurs. Constant expressions include numerals; character strings; true constants; values of enumerated types; the special constants True, False, and nil; and expressions built exclusively from these elements with operators, typecasts, and set constructors.

    ....

    This definition of a constant expression is used in several places in Delphi's syntax specification. Constant expressions are required for initializing global variables, defining subrange types, assigning ordinalities to values in enumerated types, specifying default parameter values, writing case statements, and declaring both true and typed constants.

    ....

    Typed constants, unlike true constants, can hold values of array, record, procedural, and pointer types. Typed constants cannot occur in constant expressions.

    0 讨论(0)
提交回复
热议问题