> this is because of the static allocation, right? Because the static allocation means there's one copy of the data during the entire lifetime of the program?
Yes and yes.
> Is John's solution, where the function returns void and the roll is a pointer outside the function more idiomatic C?
Pretty much wherever you need to modify a struct.
Is it any less weird in C++, just because 'this' is effectively hidden from you.
Code:
typedef struct Roll {
int dice[MAX_DICE_PER_ROLL];
int num_dice;
} Roll;
void roll_dice(Roll *roll, int num_dice) {
roll->num_dice = num_dice;
for( int i = 0 ; i < roll->num_dice ; i++ ) {
roll->dice[i] = roll_die();
}
}
int main() {
Roll roll;
roll_dice(&roll,5);
}
vs
Code:
class Roll {
int m_dice[MAX_DICE_PER_ROLL];
int m_num_dice;
public:
void roll_dice(int num_dice);
};
void Roll::roll_dice(int num_dice) {
m_num_dice = num_dice;
for( int i = 0 ; i < m_num_dice ; i++ ) {
m_dice[i] = roll_die();
}
}
int main() {
Roll roll;
roll.roll_dice(5);
}