I have this function that's a multiplexer.
// Enumerated type for a single bit.
typedef enum { FALSE=0, TRUE=1 } BIT;
BIT multi(BIT A, BIT B, BIT C, BIT D, BIT S1, BIT S0)
{
if(S1== FALSE && S0 ==FALSE)
return A;
else if(S1==FALSE && S0==TRUE)
return B;
else if (S1== TRUE && S0== FALSE)
return C;
else
return D;
}
For multiplexer, S1,S0 as a two-bit binary number, indexing into A,B,C,D, in the order given.
so like S1==0 & S0==0 refers to A and S1==0 & S0==1 refers to B etc etc.
I feel my code is close or way off or it is correct I just need to fix how I am testing it in main in which I have...
assert(multiplexer(FALSE, FALSE, FALSE, FALSE, FALSE, FALSE) == A);
assert(multiplexer(TRUE, TRUE, TRUE, TRUE, TRUE, TRUE) == D);
They're not really well designed tests, those two. Let's look at the first as an example (changing to the actual function name of multi
):
assert(multi(FALSE, FALSE, FALSE, FALSE, FALSE, FALSE) == A);
In this case multi()
should return the first argument but how would you know if it's returned one of the other three, given that they are all false. In addition, I'm not sure whether the D
variable is even available outside the function so I'm switching to a more specific value.
So a better test set would be:
assert(multi(FALSE, TRUE, TRUE, TRUE, FALSE, FALSE) == FALSE);
assert(multi(TRUE, FALSE, FALSE, FALSE, FALSE, FALSE) == TRUE);
That's for testing return of A
. For B
, C
and D
simply move the unique value to the correct position (2, 3 or 4 respectively) and change what you pass as the selector (positions 5 and 6).
Similarly for the second one, you need to re-write the test so that you can tell the difference between success and failure:
assert(multi(FALSE, FALSE, FALSE, TRUE, TRUE, TRUE) == TRUE);
assert(multi(TRUE, TRUE, TRUE, FALSE, TRUE, TRUE) == FALSE);
As an aside, I'm unsure of the usefulness in creating a special enumeration for a type that C already handles very well on its own (boolean as an int
).
It appears to me the code could be greatly simplified to:
int multi (int r0, int r1, int r2, int r3, int s0, int s1) {
if (s0) {
// Must be r2 or r3, depending on s1.
if (s1) return r3;
return r2;
}
// s0 is false, must be r0 or r1, depending on s1.
if (s1) return r1;
return r0;
}
Or, once you truly understand C :-)
// Returns rX based on sX:
// s0 false, s1 false, return r0.
// s0 false, s1 true, return r1.
// s0 true, s1 false, return r2.
// s0 true, s1 true, return r3.
int multi (int r0, int r1, int r2, int r3, int s0, int s1) {
return ((s0) ? ((s1) ? r3 : r2) : ((s1) ? r1 : r0));
}