Lazarus

Free Pascal => General => Topic started by: CM630 on July 09, 2018, 03:31:48 pm

Title: [SOLVED] „Error: Constant and CASE types do not match‟ with string
Post by: CM630 on July 09, 2018, 03:31:48 pm
Following code works right:
Code: Pascal  [Select][+][-]
  1.  
  2. procedure TForm1.Button1Click(Sender: TObject);
  3. var
  4.   A: string='';
  5.   B: string= 'B';
  6.   C: string= 'C';
  7. begin
  8.   A:=B;
  9.   case A of
  10.     'B': ShowMessage (B);
  11.     'C': ShowMessage (C);
  12.   end;
  13. end;


But this code generates „Error: Constant and CASE types do not match‟.

Code: Pascal  [Select][+][-]
  1. procedure TForm1.Button1Click(Sender: TObject);
  2. var
  3.   A: string='';
  4.   B: string= 'B';
  5.   C: string= 'C';
  6. begin
  7.   A:=B;
  8.   case A of
  9.     B: ShowMessage (B);
  10.     C: ShowMessage (C);
  11.   end;
  12. end;


B and C are strings. I tryed to cast to cast them to strings, anyway, but still I get the same error?
Is it me doing sth. wrong?
Title: Re: „Error: Constant and CASE types do not match‟ with string
Post by: RayoGlauco on July 09, 2018, 03:49:09 pm
In the second example, you use variables as selectors, instead of constants (B is a variable; 'B' is a constant). You cannot use variables as selectors.

See http://wiki.freepascal.org/Case (http://wiki.freepascal.org/Case)
Title: Re: „Error: Constant and CASE types do not match‟ with string
Post by: Thaddy on July 09, 2018, 03:50:04 pm
Needs a literal value, indeed.
Title: Re: „Error: Constant and CASE types do not match‟ with string
Post by: Gammatester on July 09, 2018, 03:50:20 pm
You should read the second part of the error message 'Error: String expression expected'. The case labels must be constants (i.e. literals or true constants). Your construct would throw equivalent message even for integer variables. The following code does work:
Code: Pascal  [Select][+][-]
  1. var
  2.   A: string='';
  3. const
  4.   B = 'B';
  5.   C = 'C';
  6. begin
  7.   A:=B;
  8.   case A of
  9.     B: writeln (B);
  10.     C: writeln (C);
  11.   end;
  12. end;
  13.  
Title: Re: „Error: Constant and CASE types do not match‟ with string
Post by: CM630 on July 09, 2018, 03:57:15 pm
Ok, thanks, I will rewrite it with
Quote
If... then.
TinyPortal © 2005-2018