ram surada
ram surada

Reputation: 61

Structure initialization in C

I am a beginner programmer in C. I have a structure which has different data types as members like int, float, bool. I am trying to initialize this struct to a value of 0.0 during initialization and also during run time for an Embedded application. I am doing member by member initialization. I cannot use memset() function as it increments the pointer by 2 bytes. I am wondering if there's an efficient way of doing this initialization.

Ex:

typedef struct _ABC_
{
       float a;
       float b;
       float c;
       int x;
       bool_t y;
}ABC;

Upvotes: 0

Views: 662

Answers (2)

Mateusz Grzejek
Mateusz Grzejek

Reputation: 12108

I cannot use memset() function as it increments the pointer by 2 bytes.

Yes, you can use memset() - it doesn't "increment" anything:

ABC abc;
memset(&abc, 0, sizeof(ABC)); //Sets sizeof(ABC) bytes to 0

The only problem with this approach is that setting all bits of floating point numbers does not mean, that their value will be equal to 0. Especially, as IEEE 754 states:

-0 and +0 are distinct values, though they both compare as equal.

So indeed, their internal representation needs to be different (and thus, neither of them may have all bits set to 0). In case of IEEE 754 it just accidentally happens, that zeroed value is equal to 0. Other FP representations may (and probably will) differ in that matter.

Because of that, you may want to initialize this struct as every POD-type:

ABC abc =
{
    0.0f, //a
    0.0f, //b
    0.0f, //c
    0,    //x
    false //y
};

Or even better:

ABC abc =
{
    0 //initializes all members to 0
};

Last example works only, if all members of this struct can be initialized with value of integral type (which is true in this particular case).

Upvotes: 7

Lv Zheng
Lv Zheng

Reputation: 324

The ISO c and ISO c++ standard say that setting all bits zero does not guarantee the floating point value to be zero. You have to explicitly assign 0.0 to it.

Also, There is no exact floating point zero. There are five distinct numerical ranges that single-precision floating-point numbers are not able to represent:

  • Negative numbers less than -(2-2e-23) × 2e127 (negative overflow)
  • Negative numbers greater than -2e-149 (negative underflow)
  • Zero
  • Positive numbers less than 2e-149 (positive underflow)
  • Positive numbers greater than (2-2e-23) × 2e127 (positive overflow)

Suggestion:

#define INFINITESIMAL 2e-149

ABC abc =
{
    INFINITESIMAL,
    INFINITESIMAL,
    INFINITESIMAL,
    0,
    false,  // You may preserve the comma at the end of the list in ISO C99
};

Upvotes: -5

Related Questions