Call a function without argument, although it needs one [K&R-C]

前端 未结 3 1989
野性不改
野性不改 2021-01-13 13:42

It\'s K&R-C and here is the code: http://v6shell.org/history/if.c

Look at the main-Method. There is this line \"if(exp())\".

But the function exp is decl

相关标签:
3条回答
  • 2021-01-13 14:10

    This is because in c

    The compiler will not be able to perform compile-time checking of argument types and arity when the function is applied to some arguments. This can cause problems

    Calling an undeclared function is poor style in C (See this) and illegal in C++

    for example-

    #include<stdio.h>
    
    void f(int x); 
    
    int main()
    {
       f(); /* Poor style in C, invalid in C++*/
       getchar();
       return 0;
    }
    
    void f(int x)
    { 
       printf("%d", x);
    }
    

    This program will work but shouldn't be used.See this Wiki link for more.

    0 讨论(0)
  • 2021-01-13 14:11

    Ultimately, it is a bug in the Unix V6 shell support command, if.

    The code for the function is:

    exp(s) {
        int p1; 
    
        p1 = e1();
        if (eq(nxtarg(), "-o")) return(p1 | exp());
        ap--;
        return(p1);
    }
    

    The function parameter s, implicitly of type int (as is the function iteself), is actually unused in the function, so the bug is the presence of s, not the absence of an argument in the calls to exp(). All the calls with zero actual arguments are correct.

    0 讨论(0)
  • 2021-01-13 14:15

    If you look at the definition:

    exp(s) {
        int p1;
    
        p1 = e1();
    
        if (eq(nxtarg(), "-o")) return(p1 | exp());
            ap--;
    
        return(p1);
    }
    
    1. s is not used
    2. C doesn't require compile time type checking. It doesn't even require function parameters to be checked. Everything is a/series of bytes

    Why does C not do any of those checks? From what I hear it's 'cause during first few years of C, computers were fairly weak. Doing those checks would require multiple passes to scan the source code, which basically increases compile time by a magnitude of n passes. So it just does a single pass, and takes every name as is, which is why function overloading is not supported

    So if the definitions did make use of s in some way, you would most likely get some horrible runtime error with wonderful outputs to the console

    0 讨论(0)
提交回复
热议问题