tags:

views:

115

answers:

3

This program supposed to find command line arguments entered on Unix which ends with “.exe”. For some reason it doesn't work. Here is the code:

 int main( int argc, char* argv[] )
{
    for ( int i = 1; i < argc; i++)
    if( findExe( argv[i] ) )
      cout << argv[i] << endl;

  return 0;
}
bool findExe( char* argument )
{
  if ( strlen( argument ) >= 4 )
    {
      string testExe = ".exe";
      string initialWord=argument; //converts c-string to string
      string temp( initialWord,( initialWord.size() - 4 ),4 );//creates temp with last four characters from initialWord

      if ( !temp.compare(testExe) )
        return true;
    }
  else
    return false;
}
+4  A: 

Remove the else, I think (although I haven't compiled the code to check). In the case where the length is at least 4, but the string comparison returns non-zero, you reach the end of the function without returning. Your compiler should have warned you: turn on more warnings.

Steve Jessop
as a side note, any idea why it is just a warning and not an error?
Naveen
If you are using gcc try compiling like this: g++ -Wreturn-type ... to see the problem with your code.
Murali VP
@Naveen: Actually, I haven't looked up whether it's an error or not, just assumed without proof that Pat's compiler is compliant in this respect. I mean "should" in the sense of "it's the kind of thing compilers frequently do notice". Assuming the compiler isn't required to reject the code, and if you're looking for a rationale, then I'd speculate it's because discovering the mistake requires a tiny amount of execution path analysis, so perhaps the standard didn't want to mandate that.
Steve Jessop
I tried it on VC9.. it gives the warning with warning level set as 1 itself.
Naveen
+2  A: 

Your findExe function is has a branch that doesn't return a result....like Steve said, compiler should've warned you.

Snazzer
Yep, if you are using gcc try compiling like this: g++ -Wreturn-type ... to see the problem with your code.
Murali VP
A: 

How about this?

bool findExe( char* argument )
{
    int n = strlen(argument);
    if (n < 4) return false;
    char* ext = argument[n-4];
    if (strcmp(ext, ".exe") == 0) return true;
    return false;
}
Shailesh Kumar