Recent

Author Topic: Default valued procedure / function parameters  (Read 3298 times)

OldProNew

  • Newbie
  • Posts: 2
Default valued procedure / function parameters
« on: July 31, 2021, 10:53:23 pm »
Why do neither of the following functions - with a default valued parameter - compile?
The compiler says "illegal expression" after the symbol "kMAX".
Probably something very trivial... but what?
(No, don't tell me the functions are silly. I know that!
Just simple examples of the problem I'm having with default valued parameters using named, typed constants as the default value. Replacing "kMAX" with "12345" makes the compiler happy, but not me https://forum.lazarus.freepascal.org/Smileys/ExcellentSmileys1/cool.gif

const kMAX: integer  = 12345 ;

function TEST1(A: integer; const B: integer = kMAX): boolean ;
begin
     TEST1 := (A <= B)
end;
function TEST2(A: integer; B: integer = kMAX): boolean ;
begin
     TEST2 := (A <= B)
end; 

jamie

  • Hero Member
  • *****
  • Posts: 4845
Re: Default valued procedure / function parameters
« Reply #1 on: August 01, 2021, 12:11:15 am »
Looks like the compiler wants only compile time constants. what you have is a writable constant and code is not generated to always read from that constant, the compiler hard codes the constant.

  Why not use overloads, have two functions of the same, a short one that calls the long one..
The only true wisdom is knowing you know nothing

FTurtle

  • Sr. Member
  • ****
  • Posts: 290
Re: Default valued procedure / function parameters
« Reply #2 on: August 01, 2021, 12:16:59 am »
Looks like the compiler wants only compile time constants.

Compiler wants real constant. Typed constant in Pascal is initialized variable.

Solution:
Code: Pascal  [Select][+][-]
  1. const kMAX = Integer(12345) ;
« Last Edit: August 01, 2021, 12:22:28 am by FTurtle »

OldProNew

  • Newbie
  • Posts: 2
Re: Default valued procedure / function parameters
« Reply #3 on: August 01, 2021, 01:20:28 am »
FTurtle...
             Thank you.

 

TinyPortal © 2005-2018