I recently encountered with an interview question. I did not understand the behaviour of printf function in this case
#include <stdio.h>
int main() {
int k = printf("String");
printf("%d",k);
}
Expected result : Compilation Error
Output : String6
Why is the output String6?
Here is the prototype for printf:
int printf(const char *format, ...);
We can see that printf returns an int.
The documentation indicates that:
Upon successful return, these functions return the number of
characters printed (excluding the null byte used to end output to
strings).
You asked why the output is "String6". Well:
printf("String");
This first prints String but does not print a newline character. Since String is 6 characters, printf returns 6, which you store in k:
printf("%d",k);
This then prints 6 (on the same line).
Try running this program:
#include <stdio.h>
int main(void)
{
int bytes_printed = printf("%s\n", "String");
// 7 = 1 + 6
printf("printf returned: %d\n", bytes_printed);
return 0;
}
Output:
String
printf returned: 7
the printf() function returns the number of character it printed. Since you set int k = printf("String");, the print function is executing printing out "String" and setting k equal to 6 since "String" is 6 characters long, then your second call to printf prints the value of k which is 6, resulting in the console displaying "String6".
This is perfectly valid C syntax.
Related
The output of the above C Language code is Rs.10.008 but why ?????
#include<stdio.h>
int main(){
unsigned i = 10;
i = printf("Rs.%d.00",i);
printf("%d",i);
return 0;
}
This statement:
i = printf("Rs.%d.00",i)
prints Rs.10.00 and returns 8 to indicate the number of characters printed. Notice that you are assigning the return value of printf to i.
Hence, the subsequent printf statement:
printf("%d",i);
Will now print 8 instead of 10. The first printf statement didn't specify an end-of-line char (\n), so it just concatenates the 8 onto the same line.
Your code has undefined behavior as you use %d for printing unsigned int. You need to use %u for unsigned (int) and %d for (signed) int.
If that is fixed we have...
For printf the C standard says:
Returns
The printf function returns the number of characters transmitted, or a negative value if
an output or encoding error occurred.
So
int i = 10; // Note unsigned changed to int
i = printf("Rs.%d.00",i);
will print "Rs.10.00" and set i to 8 because "Rs.10.00" is 8 characters long.
Then
printf("%d",i);
will print "8" so that the total output is "Rs.10.008"
printf() return the number of characters that are printed, since your code is printing 8 characters so the value assigned to i after executing first printf is 8, and since new line is not added before second printf its printing the value of i in same line resulting in Rs.10.008
first printf is printing the value of i that is 10
i=printf("Rs.%d.00",i) // it prints Rs.10.00 and assign the value of i=8
I am new to C and I have to write a loop that prints a number in words from a given integer between 0 and 9. And the loop should stop if the input is equal to '#'.
Exemple:
input: 1
output: ONE
#include <stdlib.h>
#include <stdio.h>
void main() {
char tableau[10][5] = {"ZERO","ONE","TWO","THREE","FOUR","FIVE","SIX","SEVEN","EIGHT","NINE"};
char nb[1];
while (nb[0] != '#') {
printf("nb = ");
scanf("%c", &nb[0]);
printf("%s\n", tableau[atoi(nb)]);
}
}
returns
nb = 5
FIVE
nb = ZERO
nb =
The expected output should be:
nb = 5
Five
nb =
Everything works except the line "nb = ZERO" shouldn't be there.
When the scanf line asked for input, you typed in 5<enter>, right?
So first it processed the 5, correctly, and gave output FIVE.
Then it processed the <enter> (which is character #13)
atoi(<enter>) returns 0. So it printed out ZERO.
When I print a memory address with printf %p I get address in hexdecimal - something like 0x7ffee35f5498. I am wondering why the printf return value is 16 and not the actual length of string, in this case 14?
#include <stdio.h>
int main(void)
{
char *s = "Hello World!";
int x;
x = printf("%p\n", (void*)&s);
printf("%d\n", x);
return (0);
}
output:
0x7ffeea6a3790
16
Address has 14 char but the function returned 16.
Documentation say's:
printf() : It returns total number of Characters Printed, Or negative
value if an output error or an encoding error. ...
You're not just printing the address but also a newline after it. On Linux / MacOS systems a newline is one character (0xA) while on Windows systems it is two characters (0xD 0xA).
From your comments, you say you got 15 as your output and that you're on MacOS. So that's 14 for the printed address plus 1 for the newline which is the expected result.
Update:
The original code looked a lot like this:
// printf(printf(););
#include <string>
int main()
{
printf(printf("Hello, WORLD!"););
}
However, in the original post, printf("Hello, WORLD!") was assigned to a variable, x.
Intended questions:
How do I call the return value of a function within a function? As a beginner, learning to reference a string variable using %s, I wondered how to reference a the return value of a function (for example, if the return value were a string, would I still use %s).
What does "called to print" mean? I think a simplistic explanation is: the string is put into memory and assigned an address, and the class definition tells the compiler to look up the location in memory based on the class's input-argument definition; so, the address in memory is called to print by the compiler.
Is the first argument of printf() also the return value of printf() such that x == "Hello, World!" is true in x = printf("Hello, World!")?
Original post:
I'm looking at http://www.cplusplus.com/reference/cstdio/printf/
it says: int printf ( const char * format, ... );, but it doesn't define .... So, I don't know what ... is referencing. I wrongly assumed that meant ( const char * format, const char * format, const char * format, ~. But in fact, I can't decipher the meaning based on guessing and reading.
Using this program:
#include <stdio.h>
int main(int argc, char ** argv)
{
str x = printf("Hello, World!\n");
printf("x has %d characters.\n", x);
//"x has %d characters.\n" appears first, x appears second.
return 0;
}
We see the result:
Hello, World!
x has 14 characters.
When I expected:
x has 14 characters. //because this appears first.
Hello, World! //because this appear second.
Because x comes after x has 14 characters..
Someone please explain why ./a.out is giving me the results in backwards order (using gcc and shell in Ubuntu); furthermore, eclipse is shown to give the results in this same backward order.
Perhaps another way to rephrase the question would be: where is "Hello, World!\n" being called to print?
Hello, World! appears first because you printed it first.
First (on line 4), you call printf as follows: printf("Hello, World!\n"). It prints Hello, World! and a line feed. You save the value returned by the call (14, the number of characters printed) in x.
Then (on line 5), you call printf as follows: printf("x has %d characters.\n", x). It prints x has 14 characters. and a line feed. The returned value is discarded.
Note that x has no characters; it has a number. Specifically, it has the number returned by the first call to printf, which is the number of characters it printed.
The following gives the output you desire:
const char* msg = "Hello, World!";
size_t len = strlen(msg);
printf("msg has %zu characters.\n", len);
printf("%s\n", msg);
You are trying to get the length of the string with printf but it also print's out the given string while returning printed characters length. It's not what you want.
You can use strlen instead of printf to get the length of a string without printing it to the output.
char *str = "Hello, World!\n";
int x = strlen(str);
printf("x has %d characters.\n", x);
printf(str);
return 0;
When you call printf, it will print whatever string you pass it as an argument.
So, you are getting the prints on console in the same order you placed them in your code.
Update after the edit from OP:
I still don't quite comprehend what you meant by //because this appear second. comment there.
x has 14 characters. //because this appears first.
Hello, World! //because this appear second.
My take of the problem is, What you are trying to do is get an explanation on why Hello World is printed first and then x has 14 characters. is getting printed.
I can't tell this in simplest of the words than, "Because, when the code is getting executed, processor encounters first call to printf() function with a string argument "Hello World\n". So it dumps that on console.
Then comes the second call with printf("x has %d characters.\n", x);, eventually dumping that on the console later."
Obviously, the value of x is 14 because count of chars in string Hello World! is 13+1 (i.e. 14)
Now the confusion:
If you think that you just defined x as printf("Hello World!\n"), then thats a wrong assumption.
With int x = printf("Hello, World!\n"); statement, you, in fact declared an int variable x and initialized (or assigned) it with value returned by printf("Hello World\n");, which is 14.
Consider this little program:
#include <stdio.h>
int foo(int bar)
{
printf("Foo %d\n", bar);
return 42;
}
int main() {
int x = foo(12); // we call the foo function which prints "Foo 12"
// the return value of foo is assigned to x"
printf("Hello World.\n"); // we print "Hello World"
printf("x = %d\n", x); // we print "x = 42"
}
The output is:
Foo 12
Hello World.
x = 42
If you understand this little program, you should understand also the output of your program.
In your program:
#include <stdio.h>
int main(int argc, char ** argv)
{
int x = printf("Hello, World!\n"); // you call printf which prints ("Hello World!")
// and the return value of printf is assigned to x
printf("x has %d characters.\n", x); // then we print "x has 14 characters"
return 0;
}
Hence the output is
Hello, World!
x has 14 characters.
because you called x = printf("Hello, World!\n") first;
the system will do the printf in output and also assign x = 14
therefore you have your second printf.
I have a question
"Write a C program that accepts as input a single integer k, then writes a pattern consisting of a single 1 on the first line, two 2s on the second line, three 3s on the third line, and so forth, until it writes k occurrences of k on the last line."
For example, if the input is 5, the output should be the following:
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
I have written the below code to achieve this.
#include <stdio.h>
#include <stdlib.h>
int main() {
int k = 5;
int i;
int j;
for(i = 1; i<=k; i++){
for(j = 1; j<=i; j++){
printf('%d',i);
}
printf('\n');
}
return 0;
}
When I run this program, Eclipse crashes. Is there something I am missing in the code I wrote ?
printf('%d',i);
should be
printf("%d",i);
The first argument of printf() expects const char * and what you have is a character for it. Compiler should have thrown a warning for this before you went ahead and hit a crash. Don't ignore warnings!!
You need to change
printf('%d',i);
to
printf("%d",i);
and also,
printf('\n');
to
printf("\n");
Reason: As per the man page of printf(), the function prototype is
int printf(const char *format, ...);
which says, the first argument should be a const char *.
Usually, " " is used to denote (const) char * as oppossed to ' ' which is used to denote a char constant.
Note: Enable warnings in your compiler and pay heed to them. Most of the time compiler warns you about the mistatch in agument and parameter type mismatch.
In printf, you have to pass the character pointer.
change this
printf('%d',i);
into
printf("%d",i);
printf definition.
int printf(const char *format, ...);
If you look into documentation of C programming printf function require a string i.e. const char *format, and string is represented by double quotes(" "). So replace single quotes (' ') by double quotes (" ").
The output format for printf in c library is
printf("data type representation", the data to be printed);
So in output stream you must use double quotes instead of single.
Following code will work fine,
#include <stdio.h>
int main(void) {
// your code goes here
int k,i,j;
scanf("%d",&k);
for(i=1;i<=k;i++)
{
for(j=1;j<=i;j++)
printf("%d",i);
printf("\n");
}
return 0;
}