User Tools

Site Tools


Sidebar


Introduction


Basic Tutorials


Advance Tutorials


Useful Techniques


Examples

  • Simple Pipe Weight Calculator
  • Unit Convertor

Sidebar

tutorial:procedureandfunction

This is an old revision of the document!


Procedure and Function

Procedure/Function คืออะไร

ทั้งคู่ทำหน้าที่เป็นโปรแกรมย่อยเหมือนกัน แต่มีความแตกต่างกันอยู่ดังนี้

  • Function จะส่งค่ากลับ
  • Procedure ไม่ส่งค่าใดๆกลับ



รูปแบบของ Procedure

Procedure โดยปกติจะมีอยู่ 2 แบบ คือ แบบรับค่า input กับแบบไม่รับค่า input

Topic Format
Procedure แบบไม่รับค่า Input
procedure ProcedureName;
begin
  {Do something}
end;
Procedure แบบรับค่า Input
procedure ProcedureName(Arg1,Arg2:integer; Arg3:real);
begin
  {Do something}
end;

Example-1: Procedure แบบไม่มี input

Example-1: Procedure แบบไม่มี input

procedure SayHelloWorld;
begin
  writeln('HelloWorld');
end;

Example-2: Procedure แบบมี input

Example-2: Procedure แบบมี input

procedure SayHello(Name,SurName:string; Age:integer);
begin
  writeln('Hello ',Name,' ',Surname);
  writeln('Your age is ',Age);
end;



รูปแบบของ Function

รูปแบบของ function นั้น จะคล้ายกับ procedure ทุกประการ คือมีทั้งแบบรับค่า input กับแบบไม่รับค่า input
แต่โดยทั่วไปแล้ว function มักจะถูกใช้งานโดยการรับค่า input (เพราะถ้าไม่มีการรับค่า ก็ไม่ต่างจากการใช้ค่าคงที่)
อย่างไรก็ตาม สิ่งที่ขาดไม่ได้เลยสำหรับการประกาศ function คือ ต้องมีการส่งค่า output กลับด้วยเสมอ
ตัวแปรที่ใช้รับค่าเพื่อแสดงค่า output มีได้ 2 แบบ คือ

Topic Format
Function แบบใช้ตัวแปรที่ชื่อ result เป็น Output
function FunctionName(Arg1,Arg2:integer; Arg3:real):integer;
begin
  result:= {Do something};
end;
Function แบบใช้ตัวแปรที่เป็นชื่อของฟังก์ชั่นเอง เป็น Output
function FunctionName(Arg1,Arg2:integer; Arg3:real):integer;
begin
  FunctionName:= {Do something};
end;

Example-3: Function แบบใช้ตัวแปรที่ชื่อ result เป็น Output

Example-3: Function แบบใช้ตัวแปรที่ชื่อ result เป็น Output

function multiply(a,b:real):real;
begin
  result:=a*b;
end;

Example-4: Function แบบใช้ตัวแปรที่เป็นชื่อของฟังก์ชั่นเอง เป็น Output

Example-4: Function แบบใช้ตัวแปรที่เป็นชื่อของฟังก์ชั่นเอง เป็น Output

function multiply(a,b:real):real;
begin
  multiply:=a*b;
end;



การประกาศ Procedure/Function

Procedure/Function จะต้องถูกประกาศหลังจากการประกาศตัวแปร VAR เท่านั้น โดยจะวางอันไหนมาก่อนก็ได้

tutorial/procedureandfunction.1537501738.txt.gz · Last modified: 2018/09/21 10:48 by admin