0
votes

I am using a Boolean array to check if a Char has been seen by a character occurrence check program.

My question is: How/why does/can an array boolean correlate a Char entry to true or false?

for (i = 0; i < len; i++) {
 char c = text[i];
 if (seen[c]==true) {
  continue;
 }
seen[c]=true; 

Below is code snippet that includes the 'bool' in question. Note the use of bool works here, want to know why/how.

char* text = lower_case_all();

bool seen[256];
int i;
char c;
for (i = 0; i < 256; i++) {
 seen[i]=false;
}

int len = strlen(text);

for (i = 0; i < len; i++) {
  char c = text[i];
  if (seen[c]==true) {
    continue;
  }
  seen[c]=true;
  int occs = compute_occ(c, text);
  if (occs>0) {
    printf("%c : %d : ",c, occs );
 }
}
1
c is used as an index into an array of flags indicating whether the value of c was ever seen in prior processing. This restricts invoking compute_occ to only once per any occurrence of any given value of c. Equating char with bool has nothing to do with that algorithm (which, incidentally, is rife with undefined behavior if you ever get values not in 0x00..0x7F in c, and char is signed on your platform, as it is on most).WhozCraig
Aside: bool seen[256]; .... if (seen[c]==true) { is WET. Consider coding if (seen[c]) {. It may help make code clearer.chux - Reinstate Monica
With char c, c is used as an index into array seen[]. Unfortunately, c may be negative and then seen[c] is undefined behavior (UB).chux - Reinstate Monica
The thing that puzzles me is this: "I am using a Boolean array to check if a Char has been seen by a character occurrence check program." - If you wrote this, how can you not understand and answer your own question? Surly you know why you wrote your code the way you did, right?WhozCraig

1 Answers

0
votes

C Characters are switched into their ASIC number equivalents when used as an index for an array.