문제

단일 Hello를 사용하여 condition를 두 번 인쇄 할 수 있습니까? 라코 디스

도움이 되었습니까?

해결책

라코 디스

:-)

다른 팁

라코 디스

정말 절름발이 : 라코 디스

조건문이 수행하는 작업을 알기 위해 printf의 반환 값을 조회 할 필요가 없기 때문에 쉼표 연산자를 사용하는 것이 좋습니다.이것은 가독성과 유지 보수성을 증가시킵니다.:-)

이것은 인터뷰 퍼즐처럼 들립니다.원하는 내용에 가깝기를 바랍니다. 라코 디스

Hello, World를 인쇄합니다.

안전 벨트 버클 : 라코 디스

인화 : 라코 디스

이게 무슨 뜻인가요?의심 스럽지만 적어도 가능합니다.fork를 사용하여 할 수도 있지만 분기는 다른 프로세스에서 실행됩니다.

Unix에있는 경우 : 라코 디스

인쇄물 주문을 보장하지 않는 경우

라코 디스

또는 그런 것

인터뷰에서 이러한 질문을 발견하면 최대한 빨리 도망 가세요!그러한 질문을하는 팀은 건강에 좋지 않을 수 있습니다.

편집-명확하게하는 것을 잊었습니다. 이것은 "else"가 가장 가까운 열린 "if"와 일치하고 if (CONDITION)이 아닌 "if CONDITION"으로 쓰여 있다는 사실에 의존합니다. 괄호는 퍼즐을 풀 수 없게 만듭니다..

라코 디스

참조 [ http://www.coders2020.com/what-does-printf-return]

(matt가 수정했습니다=, 감사합니다. C는 멀리 있습니다)

if 문은 제어 된 문 중 하나 또는 다른 문을 실행합니다 (예에서는 모두 printf).condition에 무엇을 사용하든, 해당 스 니펫은 "Hello"또는 "World"를 인쇄하지만 둘 다 인쇄하지는 않습니다.

편집 : 자, 트릭 질문이고 조건에 원하는 것을 넣을 수 있습니다 (원하는 모든 작업을 수행하는 전체 다른 함수에 대한 호출 포함).그러나 그것은 거의 흥미롭지 않습니다.내가 정답을 제공 한 것에 대해 실망했다고 믿을 수가 없습니다.

"else"에 주석 달기;) 라코 디스

Without knowing the return value of printf off the top of your head:

if (printf("Hello") && 0)
    printf("Hello");
else
    printf("World");

The basic answer is that in the ordinary course of events you neither want to execute both the statements in the 'if' block and the 'else' block in a single pass through the code (why bother with the condition if you do) nor can you execute both sets of statements without jumping through grotesque hoops.

Some grotesque hoops - evil code!

    if (condition == true)
    {
         ...stuff...
         goto Else;
    }
    else
    {
Else:
        ...more stuff...
    }

Of course, it is a plain abuse of (any) language because it is equivalent to:

    if (condition == true)
    {
         ...stuff...
    }
    ...more stuff...

However, it might achieve what the question is asking. If you have to execute both blocks whether the condition is true or false, then things get a bit trickier.

    done_then = false;
    if (condition == true)
    {
Then:
         ...stuff...
         done_then = true;
         goto Else;
    }
    else
    {
Else:
        ...more stuff...
        if (!done_then) goto Then;
    }
int main()
{
    runIfElse(true);
    runIfElse(false);

    return 0;
}

void runIfElse(bool p)
{
    if(p)
    {
     // do if
    }
    else
    {
     // do else
    }
}
if  (true) printf ("Hello"); if (false)
    printf ("Hello");
else
    printf("World");

No love for exit?

if(printf("HelloWorld"), exit(0), "ByeBye") 
    printf ("Hello");
else
    printf ("World");

So... you want to execute the code inside the if block... and the code inside of the else block... of the same if/else statement? Then... you should get rid of the else and stick taht code in the if.

if something
  do_this
  do_that
end

The else statement is designed to execute only if the if statement is not executed and vice-versa, that is the whole point. This is an odd question...

This could work:

if (printf("Hello") - strlen("Hello"))
    printf("Hello")
else
    printf("World")

This snippet emphasizes the return value of printf: The number of characters printed.

Just put the code before or after the if..else block.

Alternatively, if you have an "if, else if, else" block where you want to execute code in some (but not all) branches, just put it in a separate function and call that function within each block.

Solution 1:

int main(int argc, char* argv[])
{   
    if( argc == 2 || main( 2, NULL ) )
    {
        printf("Hello ");   
    }
    else
    {
        printf("World\n");
    }
    return 0;
}

Solution 2 (Only for Unix and Linux):

int main(int argc, char* argv[])
{   
    if( !fork() )
    {
        printf("Hello ");   
    }
    else
    {
        printf("World\n");
    }
    return 0;
}
 #include<stdio.h>
  int main()
{
 if(! printf("Hello"))
     printf ("Hello");
else
    printf ("World");
 return 0;
}

Because Printf returns the number of character it has printed successfully.

if(printf("Hello") == 1)
    printf("Hello")
else
    printf("World")
if (printf("Hello") < 1)
    printf("Hello");
else
    printf("World");

Greg wrote:

No matter what you use for condition, that snippet will either print "Hello", or "World", but never both.

Well, this isn't true, but why you would want it to print both, I can't find a use case for. It's defeating the point of having an if statement. The likely "real" solution is to not use an if at all. Silly interview questions... :)

Very interesting guys, thanks for the answers. I never would have thought about putting the print statement inside the if condition.

Here's the Java equivalent:

    if ( System.out.printf("Hello").equals("") )
        System.out.printf("Hello");
    else
        System.out.printf("World");

Dont use an if else block then.

EDIT to Comment.

It might then mean that the code be in both blocks, or before/after the block if it is required to run in both cases.

use a goto, one of the single most underused keywords of our day

Cheeting with an empty else statement:

if (condition)
    // do if stuff
else;
    // do else stuff

If you don't like the fact that else; is actually an empty else statement try this:

for (int ii=0; ii<2; ii++)
{
    if (condition && !ii)
        // do if stuff
    else
    {
        // do else stuff
        break;
    }
}

Two possible Solutions without using printf statements :-

First :-

#include <stdio.h>

int
main(void)
{
  if (!stdin || (stdin = 0, main()))
    printf("hello");
  else
    printf("world");
  return 0;
}

Second

#include<stdio.h>
void main()
{
if (1
#define else if (1) 
)
{ 
  printf("hello"); 
} 
else
 { 
    printf("world"); 
}
}

Reference :- Link1 , Link2

if (printf("hello") & 0)
{
printf("hello");
}
else
{
printf("world");

No need to bother about the return value of printf.

Abuse of preprocessing - with cleanup at least.


#define else 
if(1)
{
   printf("hello");
}
else
{
   printf("world");
}
#undef else

The condition to this question is:

 if(printf("hello")? 0 : 1) {   }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top