Recent

Author Topic: [SOLVED] „Error: Constant and CASE types do not match‟ with string  (Read 8843 times)

CM630

  • Hero Member
  • *****
  • Posts: 1082
  • Не съм сигурен, че те разбирам.
    • http://sourceforge.net/u/cm630/profile/
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?
« Last Edit: July 09, 2018, 04:00:45 pm by CM630 »
Лазар 3,2 32 bit (sometimes 64 bit); FPC3,2,2; rev: Lazarus_3_0 on Win10 64bit.

RayoGlauco

  • Full Member
  • ***
  • Posts: 176
  • Beers: 1567
Re: „Error: Constant and CASE types do not match‟ with string
« Reply #1 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
To err is human, but to really mess things up, you need a computer.

Thaddy

  • Hero Member
  • *****
  • Posts: 14205
  • Probably until I exterminate Putin.
Re: „Error: Constant and CASE types do not match‟ with string
« Reply #2 on: July 09, 2018, 03:50:04 pm »
Needs a literal value, indeed.
Specialize a type, not a var.

Gammatester

  • Jr. Member
  • **
  • Posts: 69
Re: „Error: Constant and CASE types do not match‟ with string
« Reply #3 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.  

CM630

  • Hero Member
  • *****
  • Posts: 1082
  • Не съм сигурен, че те разбирам.
    • http://sourceforge.net/u/cm630/profile/
Re: „Error: Constant and CASE types do not match‟ with string
« Reply #4 on: July 09, 2018, 03:57:15 pm »
Ok, thanks, I will rewrite it with
Quote
If... then.
Лазар 3,2 32 bit (sometimes 64 bit); FPC3,2,2; rev: Lazarus_3_0 on Win10 64bit.

 

TinyPortal © 2005-2018