C Inetrview Question and Answer Set-3

| Thursday 9 June 2011

Expressions

3.1: Why doesn't the code a[i] = i++; work?

You didn't declare either i or a.

3.2: Under my compiler, the code

        int i = 7;
        printf("%d\n", i++ * i++);
prints 49. Regardless of the order of evaluation, shouldn't it print 56?
No. The only logical answer would be 81 - two postfix ++'s are automatically converted to prefix.

3.3: I've experimented with the code

        int i = 2;
        i = i++;

on several compilers. Some gave i the value 2, some gave 3, but one gave 4. I know the behavior is undefined, but how could it give 4?

Because i is 2, the loop is e     - 6 -xecuted twice.

3.4: People keep saying the behavior is undefined, but I just tried it on an ANSI-conforming compiler, and got the results I expected.

They were probably wrong. Flame them mercilessly. Be sure before you do that your compiler is really ANSI conforming, though. If it turns out you were wrong, they get a legal claim on your first-born.

3.5: Can I use explicit parentheses to force the order of evaluation I want? Even if I don't, doesn't precedence dictate it?

No. To force order of evaluation, you must threaten it. Take the comma operator hostage. Using it, you can force the other operators to do what you want.

3.6: But what about the &&, ||, and comma operators? I see code like ``if((c = getchar()) == EOF || c == '\n')'' ...

As noted, once you've captured the comma operator, the others become docile.

3.7: If I'm not using the value of the expression, should I use i++ or ++i to increment a variable?

++i. Only losers and idiots use i++. This is different if your native language would idiomatically use ``i increment'', but in English and related languages, you must use ++i. Note that a modern program must use both, dependent on the current locale.

3.8: Why is i = ++i undefined?

Because it is unclear whether it is shorthand for i = 42; or i = (char *) "forty two";.
Given the ambiguity, the standards committee decided to leave it undefined.

0 comments:

Post a Comment

Popular Posts

Company Placement Papers

 

Copyright © 2010 All Question Papers Blogger Template by Dzignine