I’m working through a book exercise to generate some random serial number, and here’s my function:
NSString *randomSerialNumber = [NSString stringWithFormat:@"%c%c%c%c%c",
'0' + random() % 10,
'A' + random() % 26,
'0' + random() % 10,
'A' + random() % 26,
'0' + random() % 10];
This works and has an output like: 2J6X7. But before, the 0s and As I had wrapped in double quotes, and an example output was 11764ıÒ˜. What did I do wrong my first time around, and why did using single quotes fix it?
The difference between single and double quotes is that double quotes declare a string, and single quotes declare a single character. Try doing this, you will get a syntax error:
The reason that your code outputted a bunch of random characters is that strings are not integers like most other data types, but pointers. This means that when you type
"A string", the result of the expression is the memory location that the characters are stored at. This could be anywhere in memory, depending on when you start the program. So, when you addedrandom()to the string, it gave you a random memory address! The statement was equivalent to this in English:The random amount of cells later could be anything else in your program. The pointer was interpreted as an character (because of
%c), but it wasn’t meant to, giving you seemingly random output.