I understand how to extract the query from request line, but when I make the program, it gives me the error unused variable query although it's used later in the code. I don't know what's wrong. here is my code:

// some code

if(y == 0)
    char query[query_size + 1];
    strcpy(query, tmp);
    char query[] = "";

// some code

to understand what causes the error, you need to understand three things:

  1. the difference between defining a variable and using it.
  2. scoping.
  3. shadowing.

first off, when you use a variable that was previously defined in your code, you don't mention the type again.

int x; // define x to be of type int
x = 10; // use x (in this case, set it to 10)

second, if you define a variable within a code block (between braces), the variable, the variable will stay available to use until control hits the closing brace of the block.

if (condition)
    int x = 20;

// x = 10; // BOOM!!! x is no longer available

lastly, there is this thing called variable shadowing whereas you may define a new variable with the same type and name as an existing, in-scope variable, except that this has to be done in a more limited scope.

whenever you refer to the variable, using its name, in the more limited scope, you're gonna be referring to the new variable not the original one. in other words, the new variable shadows the original one in the more limited scope.

int x = 10; // defines original variable x

if (condition)
    int x = 20; // defines new variable x (shadows original x)
    printf("%d\n", x); // outputs 20 (i.e., x refers to new x)
} // new x is now dead (aka out of scope)

printf("%d\n", x); // outputs 10 (i.e., x refers to original x)

now the problem is that you're defining query in the else statement then control reaches the closing brace of the else statement which gets query, the variable that you just defined, to go out of scope. so basically you did nothing with that variable, hence, the compiler complaint!

more on:

  • should i use a char* to be able to modify it ? like this <code> char*t; if(condition){ t="hello"; } else {t="bye";} </code>
    – kawegan
    Oct 17 '15 at 13:24

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .