Note

深度剖析MQL4中的char, short, int和long类型

· Views 92

MetaQuotes Language 4 (MQL4)是一种为编写交易机器人、技术指标、脚本和库等用于任何MetaTrader 4终端功能的高级编程语言。在MQL4中,char、short、int和long是四种常见的整数类型,它们在内存占用和数值范围上有所不同。

char类型

char类型占用1字节(8位)内存,允许以二进制表示2^8=256个值。char类型可以包含正数和负数,值的范围是-128到127。

uchar类型

uchar类型也占用1字节内存,如同char类型,但不同的是uchar只用于表示正数。最小值为0,最大值为255。uchar类型名称中的首字母u是unsigned的缩写。

short类型

short类型的大小为2字节(16位),因此,它可以表示的值的范围等于2的16次方:2^16 = 65,536。由于short类型是有符号的,可以包含正数和负数,因此值的范围是-32,768到32,767。

ushort类型

unsigned short类型的名称为ushort,其大小也为2字节。最小值为0,最大值为65,535。

int类型

int类型的大小为4字节(32位)。最小值为-2,147,483,648,最大值为2,147,483,647。

uint类型

无符号整数类型为uint。它占用4字节内存,允许表示从0到4,294,967,295的整数。

long类型

long类型的大小为8字节(64位)。最小值为-9,223,372,036,854,775,808,最大值为9,223,372,036,854,775,807。

ulong类型

ulong类型也占用8字节,可以存储从0到18,446,744,073,709,551,615的值。

以下是这些类型在MQL4中的使用示例:

复制

char  ch = 65; 
short sh = 32000; 
int   num = 2000000000;
ulong bigNum = 9000000000000000000;

请注意,由于无符号整数类型不设计用于存储负值,所以尝试设置负值可能会导致意外的结果。例如,这样一个简单的脚本会导致无限循环:

复制

//--- 无限循环
void OnStart() 
  { 
   uchar  u_ch; 

   for(char ch=-128; ch<128; ch++) 
     { 
      u_ch = ch; 
      Print("ch = ",ch," u_ch = ",u_ch); 
     } 
  }

正确的脚本应该是这样的:

复制

//--- 正确的脚本
void OnStart() 
  { 
   uchar  u_ch; 

   for(char ch=-128; ch<=127; ch++) 
     { 
      u_ch = ch; 
      Print("ch = ",ch," u_ch = ",u_ch); 
      if(ch==127) break; 
     } 
  }

在这种情况下,尝试将-128到127的char值赋给uchar值,会发现负值被转化为了相应的正值。

在MQL4中,还可以通过十六进制表示这些值,例如:

复制

int hex1 = 0x0A; 
int hex2 = 0x12; 
int hex3 = 0X2f;
uint hex4 = 0xA3; 

以上就是对MQL4中的char、short、int和long类型的深度解析,希望对您有所帮助。


Disclaimer: The content above represents only the views of the author or guest. It does not represent any views or positions of FOLLOWME and does not mean that FOLLOWME agrees with its statement or description, nor does it constitute any investment advice. For all actions taken by visitors based on information provided by the FOLLOWME community, the community does not assume any form of liability unless otherwise expressly promised in writing.

FOLLOWME Trading Community Website: https://www.followme.com

If you like, reward to support.
avatar

Hot

No comment on record. Start new comment.