"C" Programming Language - Expressions

Started by sivaji, Jan 10, 2008, 07:12 PM

Previous topic - Next topic

sivaji

Programming Stuffs in "C" - Technical Skills for INTERVIEW

Expressions


1: Why doesn't the code a = i++; work?

You didn't declare either i or a.

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: 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 executed twice.

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.

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.

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.
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.
Am now @ Chennai