leon
leon

Reputation: 181

How does this function work "abcdefghijklmnopqrstuvwxyz" [rand()%26]?

To generate random letters of the alphabet

"abcdefghijklmnopqrstuvwxyz" [rand()%26]

How does this work?

Upvotes: 2

Views: 986

Answers (3)

Some programmer dude
Some programmer dude

Reputation: 409176

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).

Upvotes: 3

John Bode
John Bode

Reputation: 123458

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.

Upvotes: 4

Vlad from Moscow
Vlad from Moscow

Reputation: 310980

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]

Upvotes: 8

Related Questions