Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logic of ternary operator in C?

I'm studying some AES implementation C code. The encryption code needs to get the password passed as argument, and so the encrypted and the output file.

I understand it reads the password and that also treats it and turns it into a key. But there's this cycle where I can't really understand what it's doing.

int main(int argc, char **argv) {
 unsigned long rk[RKLENGTH(KEYBITS)];
 unsigned char key[KEYLENGTH(KEYBITS)];
 int i;
 int nrounds;
 char *password;
 FILE *output;
 if (argc < 3) {
  fputs("Missing argument\n", stderr);
  return 1;
 }                                              
 password = argv[1]
 for (i = 0; i < sizeof(key); i++)
  key[i] = *password != 0 ? *password++ : 0;  /* HERE IS WHERE I CAN'T GET IT */

What's exactly happening with the key string? I think there's some logical stuff and bits operations.

like image 597
diegoaguilar Avatar asked Jan 29 '26 12:01

diegoaguilar


2 Answers

The loop you are looking at is copying sizeof(key) bytes from the password string into the key buffer, and padding the rest of the buffer with 0 if the length of the password string is smaller than sizeof(key).

The ternary operator has the form:

condition ? expression-1 : expression-2

If condition is true, then expression-1 is evaluated, otherwise expression-2 is evaluated. There is short circuiting, in that only one of the expressions is ever evaluated. So, in your code:

    key[i] = *password != 0 ? *password++ : 0; 

Once *password != 0 becomes false, password does not get incremented again.

like image 86
jxh Avatar answered Jan 31 '26 00:01

jxh


For each byte in the key, if there's a corresponding byte in the password (originally argv[1]), copy that byte to the key; else copy a 0 (byte) to the key. It's a long-winded way of writing:

strncpy(key, password, sizeof(key));

(It is also one of the few times I'll ever recommend using strncpy(); in general, it doesn't do what people expect, but here, it does exactly what is required.)

like image 36
Jonathan Leffler Avatar answered Jan 31 '26 00:01

Jonathan Leffler