0

I am not sure why the following code isnt working.

I try to use gcc to compile it gcc -Wall -o test test.c, it gives me warning message: control reaches end of non void function.

But I couldn't find the error so I tried to compile it ignoring the warning messages, and tested the program out using ./test 1234321 after compiling it using gcc -o test ispalidrome.c

But instead of returning 0 (that it should to my understanding because it didn't trigger any of the if statements to return 1), it returned a random value, 46, 52, 84 etc.

The main logic behind the program is exactly as required, I just can't tell why it isn't exiting properly.

#include <stdio.h>
int main(int argc, char **argv){
    if (argc != 2){
        fprintf(stderr,  "Usage: %s \"string\"", argv[0]);
        return 1;
    }
    else{
        int i = 0;
        while( '\0' != argv[1][i] ) i++;
        char *start=argv[1];
        char *end=&start[i-1];

        while (start<end){
            if (*start != *end){
                break;
                return 1;
            }
            printf("%c is the same as %c\n",*start, *end);
            start =start+1;
            end=end-1; 
        }
    }
}
Nick
  • 1,161
  • 1
  • 12
  • 22

3 Answers3

7

Your main function is very obviously missing a return 0 at the end.

The random value it is returning is whatever happens to be in the return value register (eax on x86) when main returned.

Never turn off -Wall, and never ignore the warnings. They are your friend.


As Jim Balter and Lưu Vĩnh Phúc mentioned, the return 0 is optional in C99.

Community
  • 1
  • 1
Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
1

You're method declaration specifies that it returns an int

int main(int argc, char **argv){

You do correctly return an int at the end of your if block when you do

return 1;

but at the end of your else block there is no int returned. You can return any integer, but 0 is common for programs that naturally terminate, or you can specify a different integers to specify different exit situations.

dckuehn
  • 2,427
  • 3
  • 27
  • 37
1

Add line return 0 at the end of code. It will return proper value.

Amit
  • 81
  • 5