Reputation: 95
I have the following code in C. It is working, but I don't understand why it works. In my head it shouldn't. As you can see, I am working with two arrays, and I am 'grabbing' an element in the array with array[i] and array[j]. For array[j], I want to only test the first if and the second else if; for the array[i] I want to test only the second if, the second else if, and the last else.
The way this is written doesn't seem very elegant. What would be best practice in this case? Also, I though that C stopped testing conditions once an else if evaluated to True. If this is the case, why is the code still working when it evaluates the first else if as true; it seems to continue testing with the array[i]. (This is how I want it to work; I just don't know why it works).
for (int i = 0, j = 0; i <= numChars; ++i )
{
int index = j % keyNumChars;
if (isupper(argv[1][index]))
{
// execute code A1
}
else if (islower(argv[1][index]))
{
// execute code A2
}
if (isupper(plainText[i]))
{
// execute code B1
}
else if (islower(plainText[i]))
{
// execute code B2
}
else
{
//execute code B3
}
}
Upvotes: 0
Views: 152
Reputation: 5105
Allow me to reformat
for (int i = 0, j = 0; i <= numChars; ++i )
{
int index = j % keyNumChars;
if (isupper(argv[1][index])) {
// execute code A1
} else if (islower(argv[1][index])) {
// execute code A2
}
if (isupper(plainText[i])) {
// execute code B1
} else if (islower(plainText[i])) {
// execute code B2
} else {
//execute code B3
}
}
Upvotes: 1
Reputation: 8928
The first else
goes with the first if
, and both of those have to do with tests of j. Once those are done, the path of execution then starts over with the second if
, since it has no else
in front of it; the second if
, else if
, and else
go together, and have to do with tests of i. That should explain why both the i tests and the j tests are working.
Incidentally, the code probably needs to increment j at some point; otherwise it just keeps testing j=0 each time through.
Upvotes: 1