1

I was writing a program for infix to postfix conversion in C. In that I wrote this helper function.

int prec(char op) {
    switch(op) {
        case '+':
        case '-':
            return 1;
        case '*':
        case '/':
            return 2;
        case '^':
            return 3;
    }
}

To that I mistakenly passed a char other than those mentioned there. It didn't raise any errors and I took a lot time to detect it.

Even though I didn't mention anything for other cases, it is returning an int value. Also I suppose that it is not a garbage value, because for same input, it is giving same output in multiple runs (Eg: prec('&') -> 38). Someone please explain what is happening here.

Sourav Kannantha B
  • 2,860
  • 1
  • 11
  • 35
  • 2
    It's Undefined Behaviour. – kaylum Mar 04 '21 at 20:46
  • Welcome to the wonderful world of [*undefined behavior*](https://en.wikipedia.org/wiki/Undefined_behavior), where everything can happen, from nothing all the way to summoning [nasal demons](http://catb.org/jargon/html/N/nasal-demons.html). – Some programmer dude Mar 04 '21 at 20:47
  • 3
    *It didn't raise any errors*. Turn up compiler warnings. Any decent compiler will give a warning for that. Example warning with `gcc -Wall`: *warning: control reaches end of non-void function [-Wreturn-type]* – kaylum Mar 04 '21 at 20:47
  • If you didn't get a warning from the compiler, you need to turn up the diagnostics. If you did get a warning, you need to pay attention! – William Pursell Mar 04 '21 at 20:48
  • A decent compiler would have been able to give you a *warning* that you missed a default case. If not then you need to enable more warnings. And treat warnings as errors that must be fixed. And a good editor would have been able to remind you as well. – Some programmer dude Mar 04 '21 at 20:48
  • `gcc -Wall` and `clang` will warn about that. Plain `gcc` without options doesn't, so at least there, always always always use at least `-Wall`. – ilkkachu Mar 04 '21 at 20:48
  • 2
    It's actually legal C to not return a value, so long as the program's logic ensures that the caller won't try to use the function's return value in that case. That's why this is not an immediate fatal error. But this "feature" is mainly for compatibility with ancient code and shouldn't be used deliberately. – Nate Eldredge Mar 04 '21 at 20:52

0 Answers0