Difference between revisions of "Label"
From Free Pascal wiki
Jump to navigationJump to searchm (highlight line that triggers the jump) |
m (add Category:Code) |
||
Line 56: | Line 56: | ||
− | [[ | + | [[Category:Pascal]] |
+ | [[Category:Code]] | ||
[[Category:Control Structures]] | [[Category:Control Structures]] |
Revision as of 02:56, 13 February 2018
│
Deutsch (de) │
English (en) │
français (fr) │
русский (ru) │
The label
keyword is used for declaration of labels (markers for unconditional jumps using goto
keyword) used further in the unit
/program
.
A label
section is also required for jump targets in asm
-blocks.
0program sumExample(input, output, stderr);
1
2{ iteratively calculates the sum over first n integers }
3function iterativeSumFirstNIntegers(const n: longword): qword;
4{$ifdef CPUX86_64} // ============= optimized implementation
5// assembler modifier appended to routine declaration
6assembler;
7// you have to familiarize the compiler with symbols
8// which are meant to be jump targets
9{$goto on}
10label
11 isfni_iterate;
12{$asmMode intel}
13asm
14 xor rax, rax // rax := 0
15 // ecx is used as counter by loop instruction
16 mov ecx, n // ecx := n
17isfni_iterate:
18 add rax, qword(ecx) // rax := rax + ecx
19 loop isfni_iterate // dec(ecx)
20 // if ecx <> 0 then goto isfni_iterate
21
22 // the @result macro represents the functions return value
23 mov @result, rax // result := rax
24// note, a list of modified registers (here ['rax', 'ecx'])
25// is ignored for pure assembler routines
26end;
27{$else} // ========================== default implementation
28var
29 i: longword;
30 x: qword;
31begin
32 x := 0; // mov rax, 0
33 for i := n downto 1 do // mov ecx, n
34 begin
35 x := x + i; // add rax, ecx
36 end; // loop isfni_iterate
37 iterativeSumFirstNIntegers := x; // mov @result, rax
38end;
39{$endif}
40
41// M A I N =================================================
42var
43 n: longword;
44begin
45 readLn(n);
46 writeLn(iterativeSumFirstNIntegers(n));
47end.
Of course in a production program, you would use an algorithm applying the formula sum := (n * (n + 1)) div 2
(“Gaussian sum formula”).