Question:
What are all the problems with the following code? (In C)?
junglemanchild
2013-01-17 09:07:16 UTC
I was given the following code in a book:

for(i=0; i=128; i++)
{
if(line[i] == 0)
{
LHS++;
}
else if(line[i] == 1)
{
return;
}
return;
}

The information I have been given is that the "array line is a 128 char array and LHS is an unsigned char".

The book asks me to list all the problems that I find in the code (except sloppy presentation). Unfortunately there are no answers and I'm curious as to how many problems the code has to see if I am not picking up on something. I would appreciate it if someone who is not as amateur in C programming as me could tell me what is wrong with it. Thanks !!
Three answers:
AnalProgrammer
2013-01-17 09:21:00 UTC
The for loop has a test for continuation of

i = 128



Except this is not a test it is an assignment. As an assignment it will always be true.

It will always assign 128 to i.

The test is done first before any processing in the loop so the test

if(line[i] == 0)

will be looking at the 128 element. In an array with 128 elements that is 1 beyond the end of the array.



Have fun.
John Roland
2013-01-17 17:19:19 UTC
(1) Variables i and LHS are undefined

(2) "line" is undefined

(3) "return" does not return anything
Mammoty
2013-01-17 17:08:01 UTC
yes


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...