[Subject Prev][Subject Next][Thread Prev][Thread Next][Subject Index][Thread Index]
Re: [LI] j = ++i * ++i * ++i
Hi Aseem,
This ought to go to the interviewers, who ask such questions
in interviews ;-). First of all make the programs a little more
parser friendly, say,
j=((++i)*(++i))*(++i), or any permutations thereof.
The behaviour is entirely compiler dependent ( as you have
just proved ).
The behaviour can be explained in very simple terms as follows,
Each variable in C is allocated a fixed buffer, say when we define
a variable int i, C will request 2 bytes of memory from heap (check
sizeof - also architecture specific). This buffer may at one time
only contain a single value. Now when C parser gets an eqn. as
you have given, it can evaluate in odd varieties of ways with
surprising results,
Your case 1: Strict precedence rule followed ;-), evaluted all the
prefixes first, Buffer containing i has a value of 6. Then 6*6*6
Case 2: (++i)*(++i)*(++i) 4*5*6
Case 3: ((++i * ++i)*++i) 5*5*6
Recommended: a. Use prefix in a single line, just by itself.
b. Use brackets, which have much higher
precedence.
Recommended Reading:
1. C Programming : Kernighan and Reichie ( Forgot that spelling)
2. Practical C Programming : Steve Oualline ( - ditto -)
Suvendra
Date: Tue, 18 Jan 2000 10:03:09 -0500 (GMT)
From: Aseem Rane <aseem@xxxxxxxxxxxxxxxx>
Subject: [LI] j = ++i * ++i * ++i
if i is initialized to say 3,
what will be the value of j, where
j = ++i * ++i * ++i;
on solaris
using cc answer is
j = 6 * 6 * 6;
useing gcc answer is
j = 4 * 5 * 6;
but on linux (RH6.1 PCQ)
j = 5 * 5 * 6;
can anybody explain logic behind j's value on linux???
bye
aseem
--------------------------------------------------------------------
The Linux India Mailing List Archives are now available. Please search
the archive at http://lists.linux-india.org/ before posting your question
to avoid repetition and save bandwidth.