Note that there are some explanatory texts on larger screens.

plurals
  1. PODeclaring variables in the arguments to a function in C
    primarykey
    data
    text
    <p>I have a sort of bizarre wish; I don't know if any compiler or language extension out there allows this.</p> <p>I want to be able to declare variables inside a function invocation, like this:</p> <pre><code>int test(int *out_p) { *out_p = 5; return 1; } int main() { if (int ret = test(int &amp;var)) { // int var declared inside function invocation fprintf(stderr, "var = %d\n", var); // var in scope here } return 0; } </code></pre> <p>because then the scoping of var follows the scoping of ret. For another example (from a project I'm working on now), I have </p> <pre><code>cmd_s = readline(); int x, y, dX, dY, symA, symB; if (sscanf(cmd_s, "placeDomino:%d %d atX:%d y:%d dX:%d dY:%d", &amp;symA, &amp;symB, &amp;x, &amp;y, &amp;dX, &amp;dY) == 6) { do_complicated_stuff(symA, symB, x, y, dX, dY); } else if (sscanf(cmd_s, "placeAtX:%d y:%d dX:%d dY:%d", &amp;x, &amp;y, &amp;dX, &amp;dY) == 4) { do_stuff(x, y, dX, dY); /* symA, symB are in scope but uninitialized :-( so I can accidentally * use their values and the compiler will let me */ } </code></pre> <p>and I would prefer to write</p> <pre><code>cmd_s = readline(); if (sscanf(cmd_s, "placeDomino:%d %d atX:%d y:%d dX:%d dY:%d", int &amp;symA, int &amp;symB, int &amp;x, int &amp;y, int &amp;dX, int &amp;dY) == 6) { do_complicated_stuff(symA, symB, x, y, dX, dY); } else if (sscanf(cmd_s, "placeAtX:%d y:%d dX:%d dY:%d", int &amp;x, int &amp;y, int &amp;dX, int &amp;dY) == 4) { do_stuff(x, y, dX, dY); /* Now symA, symB are out of scope here and I can't * accidentally use their uninitialized values */ } </code></pre> <p>My question is, does any compiler support this? Does gcc support it if I rub it the right way? Is there a C or C++ (draft) spec that has this?</p> <p>Edit: just realized that in my first code example, my declaration of int ret is also no good in C99; I guess I'm spoiled by for loops. I want that feature too; imagine </p> <pre><code>while(int condition = check_condition()) { switch(condition) { ... } } </code></pre> <p>or something like that. </p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload