位置:首页 » 文章/教程分享 » D语言sizeof运算符

D语言的支持还有其他一些重要的运算符,包括的sizeof和? :。

运算符 描述 示例
sizeof 返回一个变量的大小。 a.sizeof, 其中a是整数,将返回4。
& 返回一个变量的地址。 &a; 将得到的变量actaul地址。
* 指向变量的指针。 *a; 指针变量。
? : 条件表达式 If Condition is true ? Then value X : Otherwise value Y

示例

试试下面的例子就明白了所有的D编程语言杂运算符:

import std.stdio;

int main(string[] args)
{
   int a = 4;
   short b;
   double c;
   int* ptr;

   /* example of sizeof operator */
   writefln("Line 1 - Size of variable a = %d", a.sizeof );
   writefln("Line 2 - Size of variable b = %d", b.sizeof );
   writefln("Line 3 - Size of variable c= %d", c.sizeof );

   /* example of & and * operators */
   ptr = &a;	/* 'ptr' now contains the address of 'a'*/
   writefln("value of a is  %d", a);
   writefln("*ptr is %d.", *ptr);

   /* example of ternary operator */
   a = 10;
   b = (a == 1) ? 20: 30;
   writefln( "Value of b is %d", b );

   b = (a == 10) ? 20: 30;
   writefln( "Value of b is %d", b );
   return 0;
}

当编译并执行上面的程序它会产生以下结果:

value of a is  4
*ptr is 4.
Value of b is 30
Value of b is 20