<cstddef>

offsetof

offsetof (type,member)
返回成員偏移量
此宏以函式形式返回結構或聯合型別 type 中成員 member 的位元組偏移量。

返回的值是型別為 size_t 的無符號整型值,表示指定 member 與其結構開始之間的位元組數。

引數

型別
member 是一個有效成員指示符的型別。
type 應為結構或聯合型別。
type 應為 POD 類(包括聯合)。
type 應為 標準佈局 類(包括聯合)。
成員
type 的成員。

返回值

值為 size_t 型別,表示 typemember 的偏移量。

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/* offsetof example */
#include <stdio.h>      /* printf */
#include <stddef.h>     /* offsetof */

struct foo {
  char a;
  char b[10];
  char c;
};

int main ()
{
  printf ("offsetof(struct foo,a) is %d\n",(int)offsetof(struct foo,a));
  printf ("offsetof(struct foo,b) is %d\n",(int)offsetof(struct foo,b));
  printf ("offsetof(struct foo,c) is %d\n",(int)offsetof(struct foo,c));
  
  return 0;
}

輸出
offsetof(struct foo,a) is 0
offsetof(struct foo,b) is 1
offsetof(struct foo,c) is 11


異常

無異常保證:此宏從不丟擲異常:noexcept(offsetof(type,member)) 始終為 true