3
votes

I have this function 'bintoint' which I use to convert binary number to decimal:

function bintoint(var n: string):integer;
var i: integer;
Begin
result:= 0;
Trim(n);
for i:=length(n) downto 1 do
  result := result + (strtoint(n[i])*(potencia(2,i-1)));  {Here's the source for the error, at the last 'i'}
End;

It shows a error at the i, which is the variable of the 'for' loop, declared at 'var' section. 'potencia' is another function I placed above that replaces the 'power(base,exp)' so I can calculate power with integer numbers.

function potencia(var base,exp: integer):integer;

I have seen various similar questions on the site, but their errors appear from variables at the parameters of the procedure/function and not at the variables section.

Will appreciate if you could advise me with this problem.

Thanks in advance.

1
You must pass variables to your potencia function, not constants. Or, if you're not changing base nor exp parameters inside that function, just remove the var from its definition.TLama
or declare them as const in the function.LU RD
By the by, Trim is a function that returns a new string, not a procedure that edits in place the string passed to it. As such, either just drop the var and do n := Trim(n), or replace it with const and add a new local string variable that you then assign the Trim call to.Chris Rolliston

1 Answers

5
votes

I think you have a misunderstanding of what var means in a function parameter list. In this setting var is used to indicate that the parameter is passed by reference. This means that modifications made in the function are visible to the caller. Contrast this with pass by value where modifications made in the function are do not modify the variable passed by the caller.

I have a suspicion that you think that parameters must be declared with var just as local variables are. That is not the case. Programming language keywords are often context sensitive and have different meanings depending on where they appear.

Think of a var parameter referring to the caller's variable, and a pass by value parameter as a copy of the caller's variable.

A consequence of all this is that a var parameter must be passed an actual variable. You cannot pass literal values. That is what the compiler message is telling you.

None of the parameters in you code should be var parameters. Declare the functions like this:

function bintoint(n: string):integer;
function potencia(base,exp: integer):integer;

Or perhaps pass by const. This is semantically the same as plain by value, except that the function cannot modify its local copy of the parameter.

function bintoint(const n: string):integer;
function potencia(const base,exp: integer):integer;

Finally, Trim is a function that returns the trimmed string. It does not modify its parameter. So you mean to write:

n := Trim(n);