Last active
March 4, 2022 07:51
-
-
Save morido/8637535 to your computer and use it in GitHub Desktop.
Example of weakness of -Werror=return-type in gcc
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdbool.h> | |
bool f(char achar) { | |
switch (achar) | |
{ | |
case 'q': | |
return true; | |
break; | |
case 'w': | |
return false; | |
break; | |
} | |
//We shouldn't be here | |
} | |
int main() { | |
printf("Enter a character\n"); | |
char input = getchar(); | |
/* | |
if ( !( input == 'q' || input == 'w') ) { | |
input = 'w'; | |
} | |
*/ | |
bool output = f(input); | |
if ( output ) | |
{ | |
printf("You entered q\n"); | |
} | |
else | |
{ | |
printf("You entered w\n"); | |
} | |
return 0; | |
} |
So, what happens when the user enters d
?
So, what happens when the user enters d?
Well, undefined behaviour as per my comment from 2014.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If compiled with
LANG=C && gcc -Werror=return-type gistfile1.c
this will always result inno matter if lines 21-25 are commented out or not.
If you leave out the
-Werror=return-type
, the compiled program will exhibit undefined behaviour for the return value off()
(Chapter 6.9.1, Clause 12, ISO 9899 / C99 standard).