Search code examples
cargumentscommand-line-argumentsprogram-entry-point

Misspelling "argc" as "argv" results in a comparison between a char ** and an int - why?


For the sake of simplicity, take this bit of useless code. If I try and compile the below snippet of code using clang, I get the follow error message: argc_test.c:5:14: error: comparison between pointer and integer ('char **' and 'int') [-Werror] if (argc != 4)

The code:

#include <stdio.h>

#include <stdlib.h>

int main(int agrc, char *argv[]){
    if (argc != 4){
        fprintf(stderr, "Incorrect usage."); 
    }
}

I know that the error is caused by the typo on line 5 (declaring the variable "agrc" instead of "argc". What I want to know is why does this result in the comparison of a char ** and an int in the if statement? Does this mean that argc is a char **, even though I haven't declared it?

That wasn't the only error message I got, it's just the one that stood out. Here's the full command line output:

~/workspace/week_4/pset_4/resize/ $ make argc_test

clang -fsanitize=integer -fsanitize=undefined -ggdb3 -O0 -std=c11 -Wall -Werror -Wextra -Wno-sign-compare -Wshadow    argc_test.c  -lcrypt -lcs50 -lm -o argc_test

argc_test.c:5:9: error: use of undeclared identifier 'argc'; did you mean 'argv'?
    if (argc != 4){
        ^~~~
        argv
argc_test.c:4:26: note: 'argv' declared here
int main(int agrc, char *argv[]){
                         ^
argc_test.c:5:14: error: comparison between pointer and integer ('char **' and 'int') [-Werror]
    if (argc != 4){
        ~~~~ ^  ~
argc_test.c:4:14: error: unused parameter 'agrc' [-Werror,-Wunused-parameter]
int main(int agrc, char *argv[]){
             ^
3 errors generated.
make: *** [argc_test] Error 1

Solution

  • It seems that argc is auto-corrected to argv when clang encounters the error

    argc_test.c:5:9: error: use of undeclared identifier 'argc'; did you mean 'argv'?
    

    And of course if you compare argv to 4, you are comparing a pointer to an integer.

    This kind of auto-correction is called "fix-it hints", see https://clang.llvm.org/diagnostics.html.