Wednesday, August 17, 2022

[FIXED] What will be the output of the given code below?

Issue

#include<stdio.h>

int main()
{
    int a =0, b=1, c=2;

    *( ( a+1==1) ? &b : &a) = a ? b : c;
    printf("%d, %d, %d \n", a , b, c );

    return 0;
}

Can anyone explain me the solution and output?


Solution

You can split this code into something longer but probably more readable like this:

#include<stdio.h>

int main()
{
    int a=0, b=1, c=2;
    int *ptr;

    if (a + 1 == 1) { // this will be true
        ptr = &b;
    }
    else {
        ptr = &a;
    }

    if (a != 0) { // this will be false
        *ptr = b;
    }
    else {
        *ptr = c;
    }

    printf(“%d, %d, %d \n” a , b, c );

    return 0;
}

Based on the initial values, a + 1 == 1 will be true, so ptr = &b;.

Since a=0; then a != 0 will be false and thus *ptr = c;

==> same as b = c;

So the expected output is

0, 2, 2



Answered By - Alex Lop.
Answer Checked By - Katrina (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.