-4

I tried a code today and noticed that printf("%d") still have an output. On my computer I get a output of "1487504216". I would like to know why I gets a output and what the output means. The following is the code I have tried.

#include <stdio.h>

int main()
{
    printf("%d");

    return 0;
}
龎逸傑
  • 7
  • 1

2 Answers2

4

printf("%d",... expects the next parameter to be the number to print. You did not pass it a parameter, so it will just grab the next datum from the stack and will think it is the variable to print. So you read some garbage data and print it...

Formally this is called "undefined behavior" and my explanation can be correct for some compilers and platforms, but other compilers and platforms could intercept the invalid read from the stack and abort your program, or anything else could happen: the behavior is undefined.

Paul Ogilvie
  • 25,048
  • 4
  • 23
  • 41
-1

printf returns the number of characters printed. In your case you get a weird number because your format is invalid. printf("%d", 74) would return 2 since it's printing 2 characters.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
Pavel Lint
  • 3,252
  • 1
  • 18
  • 18
  • It will return 74 – kasptom Nov 09 '19 at 12:45
  • 1
    No. If you check the actual _return value_ of the function (not what gets printed), it will be 2. Give it a try :) – Pavel Lint Nov 09 '19 at 12:45
  • You are right, it will output to the console "74" but the returned value will be 2. – kasptom Nov 09 '19 at 12:48
  • There may be two reasons for downvoting: 1. Someone like me did not tell the difference between output and the returned value, 2. The question is about the value printed out to the console and not about the value returned by the function – kasptom Nov 09 '19 at 13:04