Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turbo C++: Why does printf print expected values, when no variables are passed to it?

A question was asked in a multiple choice test: What will be the output of the following program:

#include <stdio.h>

int main(void)
{
    int a = 10, b = 5, c = 2;

    printf("%d %d %d\n");

    return 0;
}

and the choices were various permutations of 10, 5, and 2. For some reason, it works in Turbo C++, which we use in college. However, it doesn't when compiled with gcc (which gives a warning when -Wall is enabled) or clang (which has -Wformat enabled and gives a warning by default) or in Visual C++. The output is, as expected, garbage values. My guess is that it has something to do with the fact that either Turbo C++ is 16-bit, and running on 32-bit Windows XP, or that TCC is terrible when it comes to standards.

like image 479
SgrA Avatar asked Aug 22 '13 19:08

SgrA


People also ask

Why printf in C is not working?

Printf is not the thing being buffered, it's stdio, so all similar functions will behave in the same way. To demonstrate the buffering, all you have to do is printf a lot of characters, usually more than 1024, and printf will print as you will have exceeded the maximum buffer length and it will automatically fflush.

Can printf fail?

its not that printf won't always print, its that it isn't guaranteed to print immediately. This means that if you are using it for debugging purposes, then you can't guarantee that it will happen exactly when it does in the code. If you want to make sure that it does print exactly when you said it call fflush(stdout) .


2 Answers

The code has undefined behaviour.

In Turbo C++, it just so happens that the three variables live at the exact positions on the stack where the missing printf() argument would be. This results in the undefined behaviour manifesting itself by having the "correct" values printed.

However, you can't reasonably rely on this to be the case. Even the slightest change to your build environment (e.g. different compiler options) could break things in an arbitrarily nasty way.

like image 121
NPE Avatar answered Oct 23 '22 07:10

NPE


The answer here is that the program could do anything -- this is undefined behavior. According to printf()s documentation (emphasis mine):

By default, the arguments are used in the order given, where each '*' and each conversion specifier asks for the next argument (and it is an error if insufficiently many arguments are given).

If your multiple-choice test does not have a choice for "undefined behavior" then it is a flawed test. Under the influence of undefined behavior, any answer on such a multiple-choice test question is technically correct.

like image 4
cdhowie Avatar answered Oct 23 '22 06:10

cdhowie