© 2014 Firstsoft Technologies (P) Limited. login
Hi 'Guest'
Home SiteMap Contact Us Disclaimer
enggedu

C and C++ Interview Questions

2. What are conditional operators?

Ans:

The conditional operators ? and : are sometimes called ternary operators since they take three arguments. In fact, they form a kind of foreshortened if-then-else. Their general form is, expression 1 ? expression 2 : expression 3
What this expression says is: “if expression 1 is true (that is, if its value is non-zero), then the value returned will be expression 2, otherwise the value returned will be expression 3”.

Ex - 1:  What is the output?
void main()
         {
if(~0 == (unsigned int)-1)
printf(“You can answer this if you know how values are represented in memory”);
         }

 Ans:
You can answer this if you know how values are represented in memory

Explanation

~ (tilde operator or bit-wise negation operator) operates on 0 to produce all ones to fill the space for an integer. –1 is represented in unsigned value as all 1’s and so both are equal.

Ex - 2:  What is the output?
void main()
{
static int i;
while(i<=10)
(i>2)?i++:i--;
            printf(“%d”, i);
}

Ans:
32767

Explanation:

Since i is static it is initialized to 0. Inside the while loop the conditional operator evaluates to false, executing i--. This continues till the integer value rotates to positive value (32767). The while condition becomes false and hence, comes out of the while loop, printing the i value.

Ex - 3:  What is the output?
void main()
{
char ch;
for(ch=0;ch<=127;ch++)
printf(“%c   %d \n“, ch, ch);
}

Ans:
Implemention dependent

Explanation:

The char type may be signed or unsigned by default. If it is signed then ch++ is executed after ch reaches 127 and rotates back to -128. Thus ch is always smaller than 127.


SLogix Student Projects
bottom