Jump to content
Skrim

Variable not initialized?

Recommended Posts

I get this warning, what does it mean?

[dcc32 Warning] HovedUnit.pas(13295): W1036 Variable 'j' might not have been initialized

 

J is an integer.

 

Do I have to do, J:=0;

Share this post


Link to post
Posted (edited)

Depends on the context. The compiler thinks you are using J's value before you have actually assigned any value to J. Sometimes the compile makes a mistake on this, sometimes not, so it may or may not be a false positive. How are you actually using J exactly? Can you show that code? 

Edited by Remy Lebeau

Share this post


Link to post

Frequent scenario

function Test: integer;
var
  i: integer;
begin
  try
    i := 1;
    // do something
  finally;
    Result := i;
  end;
end;

i needs to be initialized before the try block.

  • Like 2

Share this post


Link to post
On 3/17/2024 at 5:31 PM, Remy Lebeau said:

Depends on the context. The compiler thinks you are using J's value before you have actually assigned any value to J. Sometimes the compile makes a mistake on this, sometimes not, so it may or may not be a false positive. How are you actually using J exactly? Can you show that code? 

Here is my code, also could it be done easier/more elegant :classic_blush:

 

//  String 000001203 to 1203

// Numbers of zeros to the left could be 1..n


function RemoveZeroLeft(var s : String) : string;
var
  i, j : integer;
begin

  for i:=1 to length(s)do
  begin
    if s<>#48 then
    begin
      j:=i;
      break;
    end;
  end;

  result:=copy(s,j,length(s));

end;

Share this post


Link to post

If the condition "if s<>#48 then" is never satisfied, then j is not initialized.
immediately after begin, initialize the variable. I use inline var for this.

  • Like 2

Share this post


Link to post
Posted (edited)

I would opt to simply eliminate J altogether:

function IndexOfFirstNotOf(const s: string; Ch: Char): Integer;
begin
  for Result := 1 to Length(s) do begin
    if s[Result] <> Ch then Exit;
  end;
  Result := 0;
end;

function RemoveZeroLeft(const s : String) : string;
var
  i : integer;
begin
  i = IndexOfFirstNotOf(s, '0');
  if i > 1 then
    Result := Copy(s, 1, MaxInt)
  else if i = 1 then
    Result := s
  else
    Result := ''; // or '0' if needed
end;

 

Edited by Remy Lebeau

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×