Reputation: 1268
I have a headerfile which declares these arrays:
int stVal_On[] = {2};
int stVal_Off[] ={1};
int subVal_On[]={1};
int subMss[]={1};
int subVal_Off[]={0};
The dereferenced arrays are then used in structs that are declared:
Definition of WriteData struct:
/* Write structure used in loop for Read- and Write Tests */
typedef struct WriteData {
char* name; // MMS object name
const VOID* data; // Data to write
const SINT32 localFormat; // SVI type (on server)
const SINT32 dataLength; // length of data to write/read
const SINT32 NbrofElmnts; // Number of elements to write/read
char* description; // SVI type as String (on server)
char* SVI_Name; // SVI address of the SVI mapped on server
UINT32 svi_Length; // length of SVI variable on server (used for readback)
} WriteData;
What is the purpose of this int arr[] = {1};
idiom? Why use arrays at all if only one value is assigned?
Upvotes: 0
Views: 82
Reputation: 134416
All the definitions create arrays with only one element, true. The actual use case may vary.
One commonly used scenario is, this variable can be passed as a function argument and it will be possible to change the content of the array (the only element value) from the called function, which in case of a non-array variable is not possible. This maybe not the very smart way, but still, it's possible and someone chose to use it.
Also, as always, array size determined by the supplied initializer leaves the room for expansion without requiring major code changes.
Upvotes: 4
Reputation: 170299
Well, one reason I can think of has to do with code organization. If you write your code in a tabular form:
struct {
char const *file_name;
uint16_t flags;
// Other data
} table [] = {
{ .file_name = "/usr/bin/foo", .flags = 0x0 },
};
for (size_t i = 0; i < sizeof(table)/sizeof(table[0]); ++i) {
// do something meaningful with a table row table[i]
}
While it's just an array of 1 now, if you need to add more cases, your code is already written well for it. You'd just need to add another "row' to the table initializer.
Upvotes: 5