#include<stdio.h>
int main() {
int d = -8623;
printf("|%6D|", d);
return 0;
}
I used my pc and ran it,the result is:|D|
,but the standard answer is:|%6D|
,same with online IDE.
#include<stdio.h>
int main() {
int d = -8623;
printf("|%6D|", d);
return 0;
}
I used my pc and ran it,the result is:|D|
,but the standard answer is:|%6D|
,same with online IDE.
Replace
printf("|%6D|", d);
with
printf("|%d|", d);
%d
is correct format for signed integers. Local PC and online IDE answers differ because you invoked undefined behavior.
The call of printf
has undefined behavior because there is used an incorrect format specifier.
To get the "expected result" you should write at least
printf("|%%6D|", d);
though the compiler can report an error because in the function call there is unused argument d
.
Why is it not the same result in this code?
How a program written in C should behave after it's compiled and executed is described in the C standard.
The draft of the standard, to which we have free access, states in C11 7.21.6.1p6 that if a printf
conversion specification is invalid, the "behavior is undefined". The %D
is an invalid conversion - there is no D
conversion specifier listed in (f)printf
description.
The term undefined behavior is defined as in C11 3.4.3p1:
behavior, upon use of a nonportable or erroneous program construct or of erroneous data, for which this International Standard imposes no requirements
There are no requirements on the code you presented. It can behave in any way, however it wants - print anything, start world war 3 or spawn dragons. More about undefined behavior can be found in this stackoverflow thread.
In case of undefined behavior in your program, anything can happen and there is no "standard answer". The result of the execution are unpredictable and can change with environment or compiler or compiler version. There is nothing strange that different environments behave differently with code with undefined behavior.
The difference you see comes from the difference in implementation of printf
on different platforms you tested. Your local printf
implementation differs from the printf
implementation available in the "online IDE" you've tried, that's why you are getting different results.