What is wrong with the following code segment?

const int limit = 100;
int eprep[limit];
int examp[limit];

for (int index = 0; index <= limit - 1; index++)
{
	eprep[index] = 0;
	examp[index] = 0;
}
if (eprep == examp)
cout << "Equal";

At first I thought it was maybe the fact that it has no 'else' but then thought that was too easy of an answer...????

Recommended Answers

All 3 Replies

if (eprep == examp)

What is it you're trying to compare? If you want to know if the contents of array eprep and array examp are the same, you must compare them element by element, keeping track of any differences.

What your statement asks is: Is the address of the first element of eprep the same as the address of the first element of examp? Is that what you really want to know?

[added]
And this line

for (int index = 0; index <= limit - 1; index++)

is a bit awkward with the <= limit -1 . Just use the strictly less than comparison to the actual array size (or limit of valid elements), as in

for ( int index = 0; index <  limit ; index++ )

There nothing wrong with code. The only thing disturbing is comparing 2 arrays in if-condition. Remember array names are pointers to the first element. So you are comparing 2 different pointers. ;)

for (int index = 0; index <= limit - 1; index++)

is a bit awkward with the <= limit -1 . Just use the strictly less than comparison to the actual array size (or limit of valid elements), as in

for ( int index = 0; index <  limit ; index++ )

It is more than a bit awkward I have seen program errors introduced by this <= limit -1 construct that are not possible with < limit .

It needs a slightly different situation but imagine that

  1. index has type unsigned rather than int

  2. limit is not a constant it is a variable of the program which has a value >= 0

I found this exact bug in a digital television receiver where presumably the original coder hadn't thought of the possibility of a channel having no audio streams at all although that is perfectly valid.

So if everything is unsigned and limit is 0 then limit - 1 is a very large number, 0xFFFFFFFF on a 32bit system and suddenly you have an infinite loop.

This error does not happen with < limit

commented: Very interesting observation. +5
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.