why formatting input output requires variable to be supplied? [duplicate] - c

This question already has answers here:
Turbo C++: Why does printf print expected values, when no variables are passed to it?
(5 answers)
Closed 9 years ago.
I have just tried to know the output without supplying the variable instead just %d and there is no error in compiling the program but i wonder how the output displayed like below.
#include <stdio.h>
int main()
{
printf("%d");
return 0;
}
The output became 7288368

"why formatting input output requires variable to be supplied?"
Because the implementation of printf demands so. From the manual page of printf:
"Each conversion specification is introduced by the character %, and ends with a conversion specifier... The arguments must correspond properly (after type promotion) with the conversion specifier."
You have used "%d" format string, which expects a integral argument appropriate for decimal conversion, yet you haven't provided any arguments, which resulted in an undefined behavior

Related

printf() working without double quotes, prints random characters [duplicate]

This question already has answers here:
Behaviour of printf when printing a %d without supplying variable name
(6 answers)
Closed 4 years ago.
I stumbled upon this C code in a college test and when I tested it on Dev-C++ 5.11 compiler, it printed random characters. I can't understand how or why this code works. Can someone enlighten me?
int main() {
char a[10] = "%s" ;
printf( a ) ;
}
This question has two parts: the missing quotes and the random characters.
printf() is just a function. You can pass strings and other values to functions as arguments. You don't have to use a literal. You can use both char *a = "something"; printf(a) (passing a variable as an argument) and printf("something") (passing a string literal as an argument).
printf() is also a variadic function. This means it can accept any number of arguments. You can use printf("hello world"), printf("%s", "hello world") and even printf("%s %s", "hello", "world"). Some older compilers don't verify you actually passed the right number of arguments based on the first argument which is the format string. This is why your code compiles even though it's missing an argument. When the program runs the code goes over the format string, sees "%s" and looks for the second argument to print it as a string. Since there is no second argument it basically reads random memory and you get garbage characters.
printf function signature is:
int printf(const char *format, ...);
It expects format string as the first argument and variable number of arguments that are handled and printed based on the format specifiers in the format string. variable a in your question is providing it the format string. Reason for random characters is that the argument for format specifier %s is missing. Following will correctly print a string:
printf( a, "Hello World!" );
A list of format specifiers can be seen here https://en.wikipedia.org/wiki/Printf_format_string
Why does it compile?
Because variadic arguments accepted by printf are processed at run time. Not all compilers do compile time checks for validating arguments against the format string. Even if they do they would at most throw a warning, but still compile the program.
It's using the string "%s" as a format string, and using uninitialized memory as the "data".
The only reason it does "something" is because the compiler was apparently not smart enough to recognize that the format string required one parameter and zero parameters were supplied. Or because compiler warnings were ignored and/or errors were turned off.
Just an FYI for anybody who bumps into this: "Always leave all warnings and errors enabled and fix your code until they're gone" This doesn't guarantee correct behaviour but does make "mysterious" problems less likely.

How the printf function works in c when format specifier is not correct? [duplicate]

This question already has answers here:
How printf works in case of type mismatch with type specifier?
(3 answers)
Closed 5 years ago.
In an Interview, I was asked the output of the following code snippet:
printf("%d", "computer");
I am a c# developer and earlier I had learned C too, but when this question was asked, I had no clue.
When I run the same question in windows 10 computer (64-bit), it is giving putput as
3571712
Please give reasons why this is happening.
It doesn't "work", what you observe is an outcome of undefined behavior.
Quoting C11, chapter §7.21.6.1/p9
[...] If any argument is
not the correct type for the corresponding conversion specification, the behavior is
undefined.
In your case, the conversion specifier is %d which expects an argument of type int but you're supplying a char*, and they are not the compatible type, hence the UB.
well value of "computer" is memory address where that string is stored. It could be value of that address is: 3571712 (But you should not rely on this - see below).
But to print memory address void* you should use %p format specifier. And using incorrect format specifiers is undefined behavior.
In an Interview, I was asked the output of the following code snippet [...]
Your answer could have been:
a. "This is undefined behavior"
b. "A number will most likely be printed, but I cannot tell you which number because I do not know where the string is stored, as the string's address will be attempted to be interpreted as an integer by the printf function".
c. "Which platform? Which compiler?"
It will not work it's giving the garbage value of these variables. And the main reason is that we use "%d" for the output of int not for string.

What will printf do when not enough arguments are passed? [duplicate]

This question already has answers here:
printf insufficient arguments
(2 answers)
Closed 6 years ago.
Let's say I used printf without passing enough arguments to match the format specifiers:
#include <stdio.h>
int main(void) {
printf("missing argument: %s\n");
}
Are there any guarantees on what the result will be?
On my machine, nothing gets printed at all.
Is this always the case, or is there a potential for it to print the string with an resolved specifier?
for example:
missing argument: %s
or:
missing argument:
The C spec is explicit on this point:
... If there are insufficient arguments for the format, the behavior is undefined. ...
C11dr §7.21.6.1 2
Are there any guarantees on what the result will be? --> No.
(On my machine, nothing gets printed at all.) Is this always the case --> No.
Is there a potential for it to print the string with an resolved specifier? --> Yes. The behavior is undefined. anything may happen.
printf reference states that passing less arguments than specified in the format yields undefined behaviour:
arguments specifying data to print. If any argument is not the type expected by the corresponding conversion specifier, or if there are
fewer arguments than required by format, the behavior is undefined. If
there are more arguments than required by format, the extraneous
arguments are evaluated and ignored

Use of % in scanf and printf [duplicate]

This question already has an answer here:
Code for printf function in C [duplicate]
(1 answer)
Closed 8 years ago.
What is the exact use of % in scanf and printf? And would scanf and printf work without the % sign? All I could find is that % is the conversion specifier but I want to know how it works actually?
% is simply the symbol used to identify the beginning of a conversion specifier in the format string; why % as opposed to any other symbol is an open question, and probably doesn't have that interesting an answer. The printf and scanf functions search the format string for conversion specifiers to tell them the number and types of additional arguments to expect, and how to format the output (for printf) or interpret the input (for scanf).
To print a literal %, you need to use %%.
printf can work without using a conversion specifier, but you'll be limited to writing literal strings. scanf is pretty useless without it.
The '%' character is used in the format string of the scanf() and print()-like functions from the standard header <stdio.h>, to indicate place holders for variable data of several kinds. For example, the format specifier "%d" is a place holder for a value having type int.
Thus, the variadic function printf() expects additional parameters passed as arguments to the function, the first of them having type int.
The value of this int argument is converted to string, and it will be replace to the place holder "%d".
In the case of scanf(), the situation is similar, but now scanf() is an input function that expects that the user enters in command-line a value fitting on the type indicated by the format specifier. Thus, a format specifier "%d" will expect that the user enters a value of type int.
Since all the arguments in C are passed by value, the input data requires you use the address of the variable, to mimic a by-reference mode of passing arguments.
There are a lot of options and details related to these format specifiers.
Yo need to take a look at the bibliography.
For example, start in Wikipedia:
printf() format string
scanf() format string
The % in a scanf() or printf() is a keyword whose purpose is identify the type of data that will be stored in the named variable. So, in the following example, the compiler would build instructions to accept input data of type integer and store it in the memory location at the address assigned to num1:
int num1;
scanf("%d",&num1);

The output of the following C program should be 3, but I am getting 0 why? [duplicate]

This question already has answers here:
Wrong output from printf of a number
(8 answers)
Closed 8 years ago.
main()
{
printf ("%d",(3.0/2)*2) ;
}
The output of the following C program should be 3. Why am I getting 0?
The directive %d expects an integer (of type int), but you're passing a floating-point value (of type double).
Depending on the compiler, the processor, the exact content of the program, and the phase of the moon, this could do anything (it's undefined behavior): crash, print some bogus value, make daemons fly out of your nose… Here, it happens that the compiler generates code that fetches an integer value from somewhere which happens to contain the value 0 at that point.
To print the floating-point value, change the printf directive:
int main(void)
{
printf ("%f", (3.0/2)*2);
}
To print an integer, convert the argument with a cast:
int main(void)
{
printf ("%d", (int)((3.0/2)*2));
}
Good compilers warn you when you make such mistakes. Make sure to turn up your compiler's warning level.
Change 3.0/2 to 3.0/2.0
printf("%d",(int)((3.0/2.0)*2));

Resources