-1

Code :

#include <stdio.h>

int main (void)
{
    int a = 1;

    switch(a) {
        int t= 4;
    case 1:
        printf("%d", t);
        break;
    default: //Does not mean anything just for clarity
        break;
    }
}

Result in C11 gcc: 1

Question: Why is this working? Isn't the compiler supposed to give an error? if a is 1, shouldn't it just jump to case 1? Why is it printing 1?

t j
  • 7,026
  • 12
  • 46
  • 66
Chris Lee
  • 49
  • 4
  • What exact compile options did you use ? And did you use -Wall to get all the warnings ? – Camion Jan 15 '18 at 04:30
  • *Why is this working?* Why do you think it is working? You think you have initialized `t` with `4` and when you print `t` you get `1`.Is it really working? – Gaurav Sehgal Jan 15 '18 at 04:30
  • 1
    I think that the people who voted to dupe the question did a rather lazy reading. – zneak Jan 15 '18 at 04:46
  • compiling the posted code causes the compiler to output: "10:9: warning: 't'' may be used uninitialized in this function [-Wmaybe-uninitialized]" Which is ALL you need to know. The code does not work as your hoping. – user3629249 Jan 15 '18 at 04:50
  • It builds because in C, variables can be used wherever in their declaring scope (curly braces) after they've been declared. `int t` within the `switch` is a directive to the compiler to reserve space for a variable, and that space exists regardless of whether the statement is executed or not. However, the variable only has a value if the statement is executed. – zneak Jan 15 '18 at 04:51
  • Reading from an uninitialized variable is not an error in C, however the value is undetermined. This means that it could be anything, and that the reason you get any specific value is not necessarily obvious or easy to explain. In general, the uninitialized value of a variable is just the value of whatever sat in the location of that variable before. – zneak Jan 15 '18 at 04:53
  • I agree with zneak : This question is not a duplicate of the other one but it HAS answers in the other question. – Camion Jan 15 '18 at 05:26
  • **Utterly wrong duplicate**, shame on you. The incorrect duplicate was even tagged with [tag:c] even though it was of **C++ only**. – Antti Haapala -- Слава Україні Jan 15 '18 at 05:59
  • Compile your code with all warnings and debug info: `gcc -Wall -Wextra -g`. You'll get warnings. Improve your code to get none. – Basile Starynkevitch Jan 15 '18 at 06:04
  • It seems this has been asked 1223421123 times already. Next time enter your **title into Google search first**. – Antti Haapala -- Слава Україні Jan 15 '18 at 06:21
  • @AnttiHaapala you missed a couple. – Martin James Jan 15 '18 at 07:13

1 Answers1

2

t has been declared in the current scope, so there is no reason to have an error. Now, but you never go through its initialisation which is made before any label, so it can have any value. What puzzles me, is if there any reason why it coincidentally equals 1.

Camion
  • 1,264
  • 9
  • 22