C

Asked • 04/28/19

This C function should always return false, but it doesn’t?

I stumbled over an interesting question in a forum a long time ago and I want to know the answer.Consider the following C function:f1.c-- #include <stdbool.h> bool f1() {  int var1 = 1000;  int var2 = 2000;  int var3 = var1 + var2;  return (var3 == 0) ? true : false; }This should always return `false` since `var3 == 3000`. The `main` function looks like this:main.c-- #include <stdio.h> #include <stdbool.h> int main() {  printf( f1() == true ? "true\\n" : "false\\n");  if( f1() )  {   printf("executed\\n");  }  return 0; }Since `f1()` should always return `false`, one would expect the program to print only one *false* to the screen. But after compiling and running it, *executed* is also displayed:<!-- language: lang-none --> $ gcc main.c f1.c -o test $ ./test false executedWhy is that? Does this code have some sort of undefined behavior?Note: I compiled it with `gcc (Ubuntu 4.9.2-10ubuntu13) 4.9.2`.

1 Expert Answer

By:

Malachi B. answered • 04/30/19

Tutor
5.0 (280)

Lead Engineer, expert in C

Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.

OR

Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.