简体   繁体   中英

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.

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.

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

Similarly :

 key[i] = *password != 0 ? *password++ : 0;  /* HERE IS WHERE I CAN'T GET IT */

 =

 if (*password != 0) { key[i]=*password++; } else { key[i]=0; } ;

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