Legit Uses of the offsetof Macro in C / C++

前端 未结 5 1680
囚心锁ツ
囚心锁ツ 2021-01-02 13:45

There is this macro offsetof in C/C++ which allows you to get the address offset of a member in a POD structure. For an example from the C FAQ:

struct foo {         


        
5条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-02 13:56

    One of the ways I've used it in embedded systems is where I have a struct which represents the layout of non-volatile memory (e.g. EEPROM), but where I don't want to actually create an instance of this struct in RAM. You can use various nice macro tricks to allow you to read and write specific fields from the EEPROM, where offsetof does the work of calculating the address of a field within the struct.

    With regard to 'evil', you have to remember that lots of stuff which was traditionally done in 'C' programming, particularly on resource-limited platforms, now looks like evil hackery when viewed from the luxurious surrounding of modern computing.

提交回复
热议问题