Skip to content

Instantly share code, notes, and snippets.

@morido
Last active March 4, 2022 07:51
Show Gist options
  • Save morido/8637535 to your computer and use it in GitHub Desktop.
Save morido/8637535 to your computer and use it in GitHub Desktop.
Example of weakness of -Werror=return-type in gcc
#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;
}
@morido
Copy link
Author

morido commented Jan 26, 2014

If compiled with LANG=C && gcc -Werror=return-type gistfile1.c this will always result in

gistfile1.c: In function 'f':
gistfile1.c:15:1: error: control reaches end of non-void function [-Werror=return-type]
cc1: some warnings being treated as errors

no 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 of f() (Chapter 6.9.1, Clause 12, ISO 9899 / C99 standard).

@mcepl
Copy link

mcepl commented Mar 3, 2022

So, what happens when the user enters d?

@morido
Copy link
Author

morido commented Mar 4, 2022

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