Recent

Author Topic: Why doesn't this compile?  (Read 648 times)

egsuh

  • Hero Member
  • *****
  • Posts: 1760
Why doesn't this compile?
« on: March 31, 2025, 04:07:18 am »
Why the assignment fails in the following example? every textbook and manual says it should work.

Code: Pascal  [Select][+][-]
  1. type
  2.    RTest = record
  3.      a, b: integer;
  4.    end;
  5.  
  6. var
  7.    ATest: RTest;
  8.  
  9. begin
  10.    ATest := (a: 1; b:2);  // <-- identifier not found a
  11.  
« Last Edit: March 31, 2025, 04:56:42 am by egsuh »

440bx

  • Hero Member
  • *****
  • Posts: 6154
Re: Why doesn't this compile?
« Reply #1 on: March 31, 2025, 04:10:17 am »
Where is variable ATest declared ?
FPC v3.2.2 and Lazarus v4.0rc3 on Windows 7 SP1 64bit.

egsuh

  • Hero Member
  • *****
  • Posts: 1760
Re: Why doesn't this compile?
« Reply #2 on: March 31, 2025, 04:57:13 am »
Haha... I deleted wrong lines. I have changed the example code above. Still, does not compile.

egsuh

  • Hero Member
  • *****
  • Posts: 1760
Re: Why doesn't this compile?
« Reply #3 on: March 31, 2025, 05:02:05 am »
Code: Pascal  [Select][+][-]
  1. type
  2.    RTest = record
  3.      a, b: integer;
  4.    end;
  5.  
  6. var
  7.    ATest: RTest = (a:1; b:2);  // I can write in this way here
  8. begin
  9.    ATest := (a:1; b:2);  // but not here.
  10.    // ...
  11. end;
  12.  

440bx

  • Hero Member
  • *****
  • Posts: 6154
Re: Why doesn't this compile?
« Reply #4 on: March 31, 2025, 05:22:30 am »
The reason that doesn't compile is because an assignment, which is what := is, allows only a single item to be assigned a value and in your example two (2) values are being assigned.

The declaration allows multiple values to be initialized but an assignment (which is a different thing) does not.

The following would compile
Code: Pascal  [Select][+][-]
  1. ATest.a := 1;  
  2.  
because only 1 variable (field in this case) is being assigned to.

A roundabout way of assigning to both fields at the same time in a single assignment can be done in this way:
Code: Pascal  [Select][+][-]
  1. var
  2.   ATest : RTest = (a:1; b:1);
  3.   BTest : RTest;
  4.  
  5. begin
  6.   BTest := ATest;  // both fields of BTest are modified
  7. end;
  8.  
Note that while fields a and b of BTest are modified, the assignment specifies only 1 variable not 2.

HTH.
FPC v3.2.2 and Lazarus v4.0rc3 on Windows 7 SP1 64bit.

 

TinyPortal © 2005-2018