3

In the book C Programming by K.N.King,

...

case 3: printf("Current balance: $%.2f\n", balance); 
        break;
case 4: return 0;
default: printf("Commands: ...");
         break;

...

Note that the return statement is not followed by a break statement. A break immediately following a return can never be executed, and many compilers will issue a warning message.

I expected my compiler (usually GCC) would issue a warning message, so I deliberately use break statement in my program right after the return statement to 0 as below.

case  4:  printf("Exit the program\n");
    return 0;
    break;      /*** My gcc compiler doesn't issue any error ***/

But my compiler didn't make any error message like below.

C:\Users\user>gcc -Wall -w -o balance balance.c
/* Normally compiled */

Does my GCC compiler have problem? If not, Did the book by K.N.K not reflect recent compiler version?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Jade_Yuwon
  • 31
  • 3
  • 1
    The part of the book you quote does not say that all compilers will issue a warning, neither that specifically gcc will issue a warning. What flags are you using during compilation? – Zois Tasoulas Feb 02 '21 at 02:41
  • 1
    I added the flags I used during compilation(-W, -Wall). I didn't mention about the flags by my fault. – Jade_Yuwon Feb 02 '21 at 02:49
  • 2
    I think it is reasonable not to warn in this case. Many people defensively always use `break` after each `case`. No need to discourage that practice. – Owen Feb 02 '21 at 02:49
  • 1
    I can't get a warning from LLVM on MacOS, either. I also tried putting `break;` after `return` in a loop, it didn't warn about that either. – Barmar Feb 02 '21 at 02:51
  • 1
    The book could simply be wrong about compilers warning about this. – Barmar Feb 02 '21 at 02:52
  • 4
    @Jade_Yuwon That's a known gcc issue, or missing feature if you want. See [Bug 46476 - Missing Warning about unreachable code after return](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=46476) and [Bug 92479 - missing warnings for unreachable codes with break](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=92479). – dxiv Feb 02 '21 at 02:53
  • Wow, thanks so much to everybody who concerned about my question, though my query was a kind of simple curiosity, I think. ^^ – Jade_Yuwon Feb 02 '21 at 02:56
  • 4
    Note that the book's most recent edition is apparently from 2008, at which time GCC did indeed have the ability to issue warnings for unreachable code. It was [removed](https://gcc.gnu.org/git/?p=gcc.git;a=commit;h=bc3c12a29c67753c473b465767b2ba6b2f7e72a6) in 2010. So indeed, the book does not reflect recent compiler versions. You might at least like to get a book that discusses C11 or C17 as there are some notable changes in the language. – Nate Eldredge Feb 02 '21 at 03:26

0 Answers0