2

To generate random letters of the alphabet

"abcdefghijklmnopqrstuvwxyz" [rand()%26]

How does this work?

Weather Vane
  • 33,872
  • 7
  • 36
  • 56
leon
  • 165
  • 2
  • 10

3 Answers3

8

In fact this expression

"abcdefghijklmnopqrstuvwxyz" [rand()%26]

is equivalent to

char *p = "abcdefghijklmnopqrstuvwxyz";

p[rand()%26]

That is a random character is selected from a string literal by using the subscript operator.

The string literal used in the original expression is implicitly converted to pointer to its first element.

The expression rand()%26 yields a random value (remainder) in the range [0, 25]

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
4

A string literal is an array expression, and as such you can subscript it like any other array expression1.

It's equivalent to writing:

const char alphabet[] = "abcdefghijklmnopqrstuvwxyz";
int idx = rand() % 26;
char c = alphabet[idx];

rand() % 26 returns a (pseudo)random value in the range [0..25], and that's used to index into the alphabet array.

You don't often see literals be subscripted like that because it's hard to read and not always obvious.


  1. Strictly speaking, the expression "decays" to type char *, and that's what the [] operator is applied to.

John Bode
  • 119,563
  • 19
  • 122
  • 198
3

String literals in C are really arrays (that as usual decay to pointers to their first element). And you can index those arrays like any other array (which is what's happening here).

S.S. Anne
  • 15,171
  • 8
  • 38
  • 76
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621