User Tools

Site Tools


Sidebar


Introduction


Basic Tutorials


Advance Tutorials


Useful Techniques


Examples

  • Simple Pipe Weight Calculator
  • Unit Convertor

Sidebar

tutorial:variableanddatatype

This is an old revision of the document!


Variables And Data Types


Variables

คือ ตัวแปร ที่ใช้ในการเขียนโปรแกรม การใช้งาน Variables จะต้องมีการประกาศตัวแปรก่อนเสมอ เพื่อให้ Compiler จองหน่วยความจำสำหรับตัวแปรนั้นอย่างเหมาะสม หลังจากนั้นจึงนำมาใช้ใส่ค่าหรือสั่งให้แสดงค่าได้ตามความต้องการ

การประกาศตัวแปร จะประกาศหลังจากคำว่า var โดยการใส่ชื่อตัวแปล แล้วตามด้วย DataType โดยการประกาศสามารถประกาศได้ทีละหลายตัว และยังประกาศพร้อมกับใส่ค่าเร่ิมต้นได้ เเช่นกัน ดังตัวอย่างต่อไปนี้

  Var
    x :integer;
    y,z :boolean; //multi-lines declaration
    a :real = 43.295; //declare with initial value

การใส่ค่าให้ Variables โดยทั่วไป จะใส่โดยใช้เครื่องหมาย “:=” ดังตัวอย่างต่อไปนี้

    x := 12;
    y := true;
    a := 902.253;



Data Types

แบ่งได้เป็น 4 ประเภท ดังนี้

Data Type Descriptions
Standard Type Integer
Real
Boolean
Character
String
User-define Type Enumerated
Sub range
Set
Structured Type Array
Record
Object
Class
Pointer Type Pointer



Standard Type

สรุปได้ดังนี้

Data Types Declaration Assign Value
Integer
var 
  x,y:integer; 
 
x:=10;
y:=$10; //Hex = 16
Real
var 
  x,y:real; 
 
x:=624.32;
y:=2E3; // = 2*10^3
Boolean
var 
  x,y:boolean; 
 
x:=true;
y:=false;
Character
var 
  x,y:char; 
 
x:='A';
y:='Z';
String
var 
  x,y:string; 
 
x:='Hello';
y:='How are you?';



User-Define Type

Enumerated Type

คือ Data Type ที่เรากำหนดชื่อได้เอง ซึ่งชื่อที่กำหนดขึ้นต้องเป็นไปตามกฎการตั้งชื่อตัวแปร ไม่ใช่ชื่อในแบบ string โดยสิ่งที่สำคัญสำหรับ Data Type ประเภทนี้ คือ ลำดับตัวเลข การประกาศ Enumerated Type ทำได้ดังนี้

Type
  TDay = (Mon,Tue,Wed,Thu,Fri,Sat,Sun);
  TDirection = (Right = 2,Left,Front = 8,Back);
  T  

การเรียกใช้งาน

VAR
  ToDay:TDay;
  Direction:TDirection;
BEGIN
  Today:=Wed;
  Direction:=LEft; //case insensitive
  
  if  Today<Sat then
    writeln('Today is not holliday')
  else
    writeln('Today is holliday');
    
  writeln('Your direction number is : ',ord(Direction));    
  readln;
END.

เราสามารถหาเลขลำดับของ Enumerated Variable ได้ โดยใช้ฟังก์ชั่น Ord() จากตัวอย่างข้างบน หากไม่มีการกำหนดลำดับให้ ลำดับก็จะเริ่มจาก 0 เสมอ จะได้ลำดับของแต่ละวันใน TDay ดังนี้

Mon=0, Tue=1, Wed=2, Thu=3, Fri=4, Sat=5, Sun=6 

สำหรับ Enumerated Variable ที่มีการกำหนดลำดับ ก็จะได้ลำดับตามที่กำหนดมา แต่สำหรบตัวที่ไม่ได้กำหนด จะนำลำดับตัวก่อนหน้ามา +1 จากตัวอย่าง TDirection จะได้ลำดับดังนี้

Right = 2, Left = 3, Front = 8, Back = 9
tutorial/variableanddatatype.1547189602.txt.gz · Last modified: 2019/01/11 13:53 by admin