¿Cuál es el tamaño de un char dado?

I've got a code that i cannot understand in C; char c is string, that supposed to be randomized, here is the question however, 26 is supposed to be range of values starting from 97, but it easy to understand for integer, but in case of char i have no clue what it is supposed to be

char c = (char) rand() % 26 + 97;

preguntado el 28 de mayo de 14 a las 14:05

If your question is about c, please tag it c, not c# -

3 Respuestas

That is generating a random character. En ASCII, alphabetical characters start at 97. So, the code is taking 97, adding a random number between 0 and 25 to it, then casting it to a char, which generates a random alphabetical character.

contestado el 28 de mayo de 14 a las 15:05

I've got it now, it generates random decimal value of a single character using ASCII table. Much appreciated! - evaldo

Minor: rand() % 26 --> random number between 0 and 25 (inclusive). - chux - Reincorporar a Monica

It is unlikely that ASCII libraries are used; more likely, Windows-1252 (or equiv) or UTF-8. For A-Z, the values are the same, but it's important to know which character set and encoding one is using and it is almost certainly not ASCII. - Tom Blodget

97 = ascii 'a'

It generates a random character between 'a' y 'z' inclusivo.

Ref: Valores ASCII

contestado el 28 de mayo de 14 a las 14:05

It's a bad, non-portable way to generate a random character by directly computing the código ASCII.

A better, more portable, way is to randomize the index into a table of characters. This pushes the responsibility for what code is used to represent each character into the compiler, where it belongs:

char random_char(void)
{
  const char alpha[] = "abcdefghijklmnopqrstuvwxyz";

  return alpha[rand() % sizeof alpha];
}

Any decent compiler will very likely inline the above.

NOTA Usar % to range-limit the return value of rand() is generally frowned upon, but that's not the focus here.

contestado el 28 de mayo de 14 a las 15:05

haría static be useful here as in static const char alpha[] = "abcdefghijklmnopqrstuvwxyz";? - chux - Reincorporar a Monica

@chux It would of course work, but I don't think it adds much benefit in practice. static signals "I want this variable to keep its value between invocations", but here the value is const so it's kind of moot. I expect the compiler to implementar it by moving it to the data segment, there shouldn't be any initialization overhead or such. Using static then feels like premature optimization and overcomplicating things, to me. I might be wrong, haven't read compiler output for this case lately. - relajarse

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.