5 ms·
Can someone tell me how this works? It’s from parser.c but I just want a general idea of the C construct itself. const char *src = is_static(l) ? l->val_st
by tomcam 4y ago
Can someone tell me how this works? It’s from parser.c but I just want a general idea of the C construct itself.
const char *src = is_static(l) ? l->val_str : is_strbuf(l) ? (char*)l->val_strb->cstr + l->strb_off : (char*)l->val_chr;
- deleted 4y ago[deleted]
- i_don_t_know 4y ago(a ? b : c) means (if a then b else c). The line is a nested if-else construct: if l is static string (?) then src = l->val_str else if l is a string buffer then src = l->val_strb_cstr + l->strb_off else src = l->val_chr
- jfoutz 4y ago?: Is like if, but it’s an expression rather than a statement so it can go lots of places. I can’t see where l is declared. I’d guess it is a union. The tests figure out what kind of structure is passed in. either a plain old c string, a cstring in a big buffer, or a char. I think that’s the gist in words. Kinda like a match expression over a sum type
- infradig 4y agoWell l is a cell pointer to a list. The nested if-then-else is riffing on the cell's tag to hide all the numerous internal representations for an atom/string, eg. intern'd to cell, in fixed atom-table, as malloc'd C-string, as slice of some other string or somewhere in a mmap'd file. It's ugly, but that's C sometimes... the ugly truth.
- tomcam 4y agoThanks, all. I recognized the ternary operator but should have been clearer. I am flummoxed as to what happens at compile time. This looks like a variable declaration but with executable code??