HiveBrain v1.2.0
Get Started
← Back to all entries
patterncMinor

Attempting a fluent API for creating random int arrays

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
randomarrayscreatingapiintattemptingforfluent

Problem

I have attempted doing a fluent API for creating random int arrays, and the following is what I came up with:

fluent_arrays.h:

```
#ifndef FLUENT_ARRAYS_H
#define FLUENT_ARRAYS_H

#define REQUEST_THREAD_LOCAL 1

#ifdef REQUEST_THREAD_LOCAL
#define THREAD_LOCAL __thread
#else
#define THREAD_LOCAL
#endif

/*****
The maximum integer selector.
*****/
typedef struct {
int (with_maximum)(const int maximum);
} maximum_selector;

/*****
The minimum integer selector.
*****/
typedef struct {
maximum_selector (with_minimum)(const int minimum);
} minimum_selector;

/*****
The array length selector.
*****/
typedef struct {
minimum_selector (of_length)(const size_t length);
} size_selector;

/*****
Thread specific state.
*****/
static THREAD_LOCAL int tl_api_initialised = 0;
static THREAD_LOCAL int tl_minimum;
static THREAD_LOCAL size_t tl_length;

/*****
Global state.
*****/
static size_selector gl_size_selector;
static minimum_selector gl_

Solution

Range limits of integer math: rand() % (maximum - minimum + 1).

Should the user have minimum == 0 and maximum == RND_MAX ( a reasonable situation) which might be INT_MAX, then code is attempting undefined behavior with rand() % (INT_MAX + 1). Also it is easy enough for the width of the inclusive range [minimum ... maximum] to be greater than INT_MAX. A simple solution is to resort to a wider integer type. Example: int2x

// some wider type
int2x diff = (int2x) maximum - minimum + 1;
p_array[i] = rand() % diff + minimum;


Now diff could exceed the range of [0 ...RND_MAX]. In that case repeated calls to rand() (or other advanced schemes) are needed.

// Not highly efficient, but to show the point.
int2x r = (int2x) rand() * ((int2x) RND_MAX + 1) + rand();
p_array[i] = r % diff + minimum;


Using % can introduce random number generation bias. I'll assume OP is familiar with that. Many posts in SO discuss that like Generating random numbers in C

Minor: create_random_array() --> create_random_array(void) as the function should not accept any parameters.

Code Snippets

// some wider type
int2x diff = (int2x) maximum - minimum + 1;
p_array[i] = rand() % diff + minimum;
// Not highly efficient, but to show the point.
int2x r = (int2x) rand() * ((int2x) RND_MAX + 1) + rand();
p_array[i] = r % diff + minimum;

Context

StackExchange Code Review Q#86266, answer score: 2

Revisions (0)

No revisions yet.