It's a part of my program
for (i=0;i<strlen(a);++i)
for(j=0;j<strlen(b);j++){
if(a[i]==b[j]){
goto oopoo;
}
}
oopoo: printf("YES");
my problem: I want when one common character in any position is the same for array a and array b , my loop terminates and print yes.
when I use break in inner "if" it just terminates if and then checks for other i and j.
so I used goto . but it prints "yes" even when there is not common character between array a and array b.
how can I solve it?
Copyright © 2025 Q2A.ES - All rights reserved.
Answers & Comments
Verified answer
Using goto is VERY bad, don't get used to it.
Having said that:
for (i=0;i<strlen(a);++i)
for(j=0;j<strlen(b);j++){
if(a[i]==b[j]){
goto oopoo;
}
}
goto noopoo;
oopoo:;printf("YES");
noopoo:
OR
for (i=0;i<strlen(a);++i)
for(j=0;j<strlen(b);j++){
if(a[i]==b[j]){
printf("YES");
goto oopoo;
}
}
oopoo:;
OR
bool found = false;
for (i=0;i<strlen(a) && !found;++i)
for(j=0;j<strlen(b) && !found;j++){
found = (a[i]==b[j]);
}
if (found) {
printf("YES");
}
You're going to get condescending responses about how goto is evil. From programmers who use disguised goto operations like break, continue and return, no less.
This is a case where goto is superior to structure. Add a boolean to indicate success or failure of the search:
bool found_it = false;
for (i=0; i<strlen(a); ++i) {
.... for (j=0; j<strlen(b); j++) {
.... .... if (a[i]==b[j]) {
.... .... .... found_it = true;
.... .... .... goto oopoo;
.... .... }
.... }
}
oopoo:
if (found_it) printf("YES\n");
I added ".... " tokens to represent indent levels (pretend they're tabs or spaces) and a few extra spaces as well.
For the record, the "official" solution is to use that found_it boolean in the for statement, as in:
for (i=0; i<strlen(a) && !found_it; ++i) {
.... for (j=0; j<strlen(b) && !found_it; j++) {
.... .... if (a[i]==b[j]) {
.... .... .... found_it = true;
.... .... }
.... }
}
That runs substantially slower on a large array, since the boolean must be tested frequently in the loop. If must remove the goto to make a purist happy, remove the "&& !found" from the innermost loop and put a break (a goto in all but name) in after setting the boolean.
for (i=0; i<strlen(a) && !found_it; ++i) {
.... for (j=0; j<strlen(b); j++) {
.... .... if (a[i]==b[j]) {
.... .... .... found_it = true;
.... .... .... break; /* escape the inner loop */
.... .... }
.... }
}
The outer loop will still test found_it and stop when it's true. You get much of the performance, without the clarity of the goto.