This shows you the differences between two versions of the page.
Both sides previous revision Previous revision Next revision | Previous revision Next revision Both sides next revision | ||
tutorial:procedureandfunction [2019/01/04 15:56] admin |
tutorial:procedureandfunction [2019/01/04 21:11] admin |
||
---|---|---|---|
Line 147: | Line 147: | ||
end; | end; | ||
</sxh> | </sxh> | ||
+ | |||
+ | |||
+ | <hidden Example-6: Passing Parameters (By Value, By Reference)> | ||
+ | <sxh delphi;> | ||
+ | program Passing_Param; | ||
+ | |||
+ | var A,B:integer; | ||
+ | |||
+ | procedure DoItA(X:integer); //By Value | ||
+ | begin | ||
+ | X:=100; | ||
+ | writeln('DoItA, X = ',X); | ||
+ | end; | ||
+ | |||
+ | procedure DoItB(var X:integer); //By Reference | ||
+ | begin | ||
+ | X:=200; | ||
+ | writeln('DoItB, X = ',X); | ||
+ | end; | ||
+ | |||
+ | begin | ||
+ | A:=1; | ||
+ | B:=2; | ||
+ | |||
+ | writeln('A = ',A); | ||
+ | writeln('B = ',B); | ||
+ | |||
+ | DoItA(A); | ||
+ | DoItB(B); | ||
+ | |||
+ | writeln('A = ',A); | ||
+ | writeln('B = ',B); | ||
+ | |||
+ | readln(); | ||
+ | end. | ||
+ | </sxh> | ||
+ | |||
+ | Compiled Results: | ||
+ | |||
+ | A = 1 | ||
+ | B = 2 | ||
+ | DoItA, X = 100 | ||
+ | DoItB, X = 200 | ||
+ | A = 1 | ||
+ | B = 200 | ||
+ | | ||
+ | </hidden> | ||
+ | \\ | ||
+ | |||
+ | =====Forward Declaration===== | ||
+ | คือ การประกาศ Procedure/Function ล่วงหน้าเพื่อให้ทุก Procedure/Function สามารถเรียกใช้งานกันและกันได้หมด สาเหตุที่ต้องทำแบบนี้เพราะว่า โดยปกตินั้น Compiler จะอ่าน source code จาก บนลงล่าง ดังนั้น หากมี Procedure/Function ตัวใดตัวหนึ่งเรียกใช้งาน Procedure/Function ตัวอื่นที่ยังไม่ได้ประกาศ จะทำให้เกิด Error \\ | ||
+ | |||
+ | รูปแบบการประกาศสำหรับ Program จะมีคำว่า forward ต่อท้ายดังนี้ | ||
+ | |||
+ | Procedure ProcedureName; forward; | ||
+ | |||
+ | |||
+ | <hidden Example-7: Forward Declarations on Simple Program> | ||
+ | __**อธิบาย**__ - ตัวอย่างนี้ มีการประกาศโปรแกรมย่อย ชื่อ Second ล่วงหน้า เพื่อให้โปรแกรมย่อยที่ชื่อ First ได้รู้จัก Second ก่อน | ||
+ | |||
+ | <sxh delphi;> | ||
+ | program FWD_Declaration; | ||
+ | |||
+ | //Forward declarations | ||
+ | procedure Second; forward; | ||
+ | |||
+ | //Implementations | ||
+ | procedure First; | ||
+ | begin | ||
+ | writeln('Hello First'); | ||
+ | Second; | ||
+ | end; | ||
+ | |||
+ | procedure Second; | ||
+ | begin | ||
+ | writeln('Hello Second'); | ||
+ | end; | ||
+ | |||
+ | begin | ||
+ | First; | ||
+ | readln(); | ||
+ | end. | ||
+ | </sxh> | ||
+ | |||
+ | Compiled Results: | ||
+ | |||
+ | Hello First | ||
+ | Hello Second | ||
+ | | ||
+ | </hidden> | ||
+ | \\ |