简体   繁体   中英

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

To generate random letters of the alphabet

"abcdefghijklmnopqrstuvwxyz" [rand()%26]

How does this work?

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]

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM