din2
din2

Reputation: 195

Strange expression

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.

Upvotes: 18

Views: 591

Answers (5)

gbulmer
gbulmer

Reputation: 4290

that is not the whole expression i % j + 1 is (i%j)+1 so that is (arc4random() % (126-'!'+1)) + '!'

Doh! I should just post answers ROFL :-)

Upvotes: 1

glglgl
glglgl

Reputation: 91017

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

Upvotes: 32

kailoon
kailoon

Reputation: 2069

I believe they are just trying to limit the result to printable characters. Basically it is limiting the range of random numbers to everything between the character "!" and "~".

Upvotes: 1

Karoly Horvath
Karoly Horvath

Reputation: 96258

this is evaluated based on operator precedence like this:

(arc4random() % (126-'!'+1)) + '!';

Upvotes: 4

socha23
socha23

Reputation: 10239

% has higher precedence than +, so your expression isn't same as

arc4random() % ((126-'!'+1)) + '!'),

but it's the same as

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

First version can return values lower than 33, while second one can't.

Upvotes: 2

Related Questions