开发者

Explain the output of following?

#include<stdio.h>
void main()
{
    char ch;
    if((ch=printf(1234))
        printf("A");
    else
        printf("B开发者_开发百科");
}

Answer is B : But i don't know what value is assigned to ch and what happens to printf(1234)


From the printf(3) man page:

Return value
   Upon successful return, these functions return the number of characters
   printed  (not  including  the  trailing  '\0'  used  to  end  output to
   strings).


You could learn to use a debugger and see what value has been assigned to ch. Or you could add printf("%d\n", ch); at the and of your program and see it that way.

Or you could read the documentation, like Ignacio Vazquez-Abrams pointed out.


printf returns the number of characters written in the output. However, you have several errors in your code. It should look like this:

#include<stdio.h>
int main()
{
    int ch;
    if(ch=printf("1234"))
        printf("A");
    else
        printf("B");

    return 0;
}

In this case ch will be 4, and the output should be 1234A.

UPDATE: modified based on the received comments.


I'd like to point out that your code might not compile on most modern compilers, particularly because of line 5.

But assuming your compiler lets you do so, the printf will return 0 (this is your ch), since nothing was printed. Hence, answer is B.


The signature of printf is

int printf(const char* restrict fmt, ...)

and you've passed an integer for the first argument.

The behavior of printf(1234) is undefined Implementation defined.

5. An integer may be converted to any pointer type. Except as previously specified, the result is implementation-defined, might not be correctly aligned, might not point to an entity of the referenced type, and might be a trap representation. (6.3.2.3 Pointers)

The behavior is undefined when 1234 happens to point to a valid string that contains format specifiers.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜