PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, August 17, 2022

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

 August 17, 2022     c, operators, output, pointers     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing