wrote:
> On Jul 9, 10:30 am, Robert Bauck Hamar <roberth+n...@ifi.uio.no>
> wrote:
>> cougr...@gmail.com wrote:
>> > I've got a take home final for my computer class and it has a bonus
>> > question concerning
>> > some programming that we didn't have time to cover. I've already got
>> > an A in the class, so
>> > it won't affect my grade one way or another, however my obsessive/
>> > compulsive tendencies
>> > just can't let it go. Could I get some help in explaining what this
>> > code snippet does;
>>
>> > char foo[8]=" bcd f\n\0";
>> > int i=2;
>>
>> > while (foo[i++]) putchar(foo[i]);
>>
>> Why don't you try it?
> Well, I don't have access to C so I can't try it.
This is a C++ newsgroup, so you don't need C.
> From what I've been
> able to glean from the book is that its declaring an array of 8
> integers
Yes. The integers are of type char.
Then this array is initialised with nine elements, which is an error. You
are not allowed to initialise an array with more elements than it can hold.
Thus, the answer to your question: It does not compile.
> and increasing it by 2 during each loop.
You can't increase an array.
> I don't understand the 'bcd'
> part.
bcd stands in between the double quotes, so those characters are part of a
string literal: " bcd f\n\0".
> Can someone give me a hand?
If we change your example to this:
#include <stdio.h>
int main() {
char foo[/*look nothing*/] = " bcd f\n\0";
int i=2;
while (foo[i++]) putchar(foo[i]);
}
then
char foo[/*look nothing*/] = " bcd f\n\0";
defines foo to be a char array of nine elements:
' ' (space), b, c, d, ' ', f, \n (newline character), \0 (character with
value 0), and \0 (This is an extra 0. String literals always hold an extra
0 at the end.)
So foo[0] == ' ', foo[1] == 'b', foo[2] == 'c' ... foo[8] == char(0).
int i=2;
defines i to be an int, and initialises it to 2.
while (foo[i++]) putchar(foo[i]);
1. Checks whether the ith element of foo is not zero.
2. Increments i.
3. If the test in 1 was true, it writes the (new) ith element of foo to the
standard output stream. If the test was false, it continues.
}
returns the value 0 to the environment.
--
rbh