Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange expression

Tags:

c

I have found this line of code in a game that I study

int charaCode = arc4random() % (126-'!'+1)+'!';

I know what arc4random is but the expression is strange to me.

What is the purpose of

(126-'!'+1)+'!'

It always evaluates to 127.

like image 716
din2 Avatar asked Mar 23 '12 15:03

din2


1 Answers

You interpreted it wrong: the % operator has a higher precedence than +.

So, in effect, you have:

int charaCode = (arc4random() % (126-'!'+1))+'!';

which clips the function result to 0..93 and shifts it so that it starts with '!'.

So the effective range of what you get is 33..126 (which is the range of all visible ASCII characters from ! to ~).

like image 196
glglgl Avatar answered Nov 15 '22 20:11

glglgl