Actually, your code would've blown up for two reasons:
double foo[13] ;
foo[14] = 1.23 ;
printf("%f\n", foo[14]) ;
First, remember that all arrays in C (C++, Java, too) begin with zero. So, the indices for foo range from 0 to 12. Trying to go foo[14] = 1.23; /* you probably meant foo[13] = 1.23; would cause an out of bounds error in part because of the "off by one error." In either case, you're going to experience a serious error. Depending on the OS, you might have a crash, memory corruption at the location just past the end of the array, or a General Protection Fault.
As for your second code example, that's exactly the technique I taught beginning C programmers for years. Not only does it prevent out of bounds errors, the code is much more maintainable. If the upper limit changes, all you have to do is change the #define N_limit value and recompile.
As a style issue, I've always preferred putting the opening brace at the same level of indention as the corresponding close brace. It just makes it easier to see that everything lines up properly. Sure, your printouts will be a bit longer but it makes errors easier to spot, IMO.
(don't know if the formatting will work properly here)
for (i=0; i < N_limit; i++)
{
foo[i] = i; /* should be tabbed over one level */
}
Of course, for a statement this simple, you could also go
for(i=0; i < N_limit; foo[i]=i++);
C++ and Java let you take it a step further by combining the int declaration into the loop:
for(int i=0; i < N_limit; foo[i]=i++);
Space/Science » in reply to It's like the "array out of bounds" bug in C programming
re: It's like the "array out of bounds" bug in C programming
The whole thread (45 posts)
- a comment on the go for shuttle launch
- re: a comment on the go for shuttle launch
- re: a comment on the go for shuttle launch
- my view as posted on msnbc.com
- Could you imagine what the doctors would say if you had a backup heart?
- Intermittent problems are tough to fix
- re: Intermittent problems are tough to fix
- It's like the "array out of bounds" bug in C programming
- which is itself the best argument against C.
- re: It's like the "array out of bounds" bug in C programming
