IT이야기

함수 선언: K&R vs ANSI

cyworld 2022. 6. 16. 22:19
반응형

함수 선언: K&R vs ANSI

K&R 함수 선언과 ANSI 함수 선언의 차이점은 무엇입니까?

K&R 구문은 구식이므로 매우 오래된 코드를 유지할 필요가 없는 한 생략할 수 있습니다.

// K&R syntax
int foo(a, p) 
    int a; 
    char *p; 
{ 
    return 0; 
}

// ANSI syntax
int foo(int a, char *p) 
{ 
    return 0; 
}

레거시 K&R 스타일의 선언/정의

Kernighan과 Ritchie가 "The C Programming Language"를 처음 출판했을 때 C는 아직 완전한 기능의 프로토타입을 제공하지 않았습니다.함수의 순방향 선언이 존재했지만 반환 유형을 나타내는 유일한 목적을 가지고 있었습니다.반환된 함수의 경우intC99까지는 필요하지 않았습니다.

C89까지, 매개변수 유형(및 암묵적으로 그 수)을 지정하는 함수 프로토타입의 개념이 추가되었다.프로토타입도 함수 선언의 일종이기 때문에 비공식 용어인 "K&R 함수 선언"은 프로토타입이 아닌 함수 선언에 사용되기도 한다.

// K&R declarations, we don't know whether these functions have parameters.
int foo(); // this declaration not strictly necessary until C99, because it returns int
float bar();

// Full prototypes, specifying the number and types of parameters
int foo(int);
float bar(int, float);

// K&R definition of a function
int foo(a)
    int a; // parameter types were declared separately
{
    // ...
    return 0;
}

// Modern definition of a function
float bar(int a, float b) 
{
    // ...
    return 0.0;
}

우발적인 K&R 선언

C에 처음 온 사람은 완전한 프로토타입을 사용하려고 할 때 실수로 K&R 선언을 사용할 수 있습니다.왜냐하면 빈 파라미터 리스트는 다음과 같이 지정해야 한다는 것을 깨닫지 못할 수 있기 때문입니다.void.

함수를 선언하고 정의하는 경우:

// Accidental K&R declaration
int baz(); // May be called with any possible set of parameters

// Definition
int baz() // No actual parameters means undefined behavior if called with parameters.
          // Missing "void" in the parameter list of a definition is undesirable but not
          // strictly an error, no parameters in a definition does mean no parameters;
          // still, it's better to be in the habit of consistently using "void" for empty
          // parameter lists in C, so we don't forget when writing prototypes.
{
    // ...
    return 0;
}

...그렇다면 실제로는 파라미터를 사용하지 않는 함수의 프로토타입을 제공하는 것이 아니라 알 수 없는 유형의 파라미터를 받아들이는 함수에 대한 K&R 스타일의 선언을 제공하는 것입니다.

ANT는 이 같은 질문에 대해 이 구문은 권장되지 않지만 C99 시점에서는 여전히 유효하다고 지적합니다(또한 함수의 수와 파라미터 유형을 알 수 없는 함수에 대한 함수 포인터에는 아직 잠재적인 응용 프로그램이 있습니다).따라서, 정의되지 않은 동작의 위험이 높지만, 호환 컴파일러는 기껏해야 함수가 decl일 경우 경고를 생성합니다.적절한 프로토타입 없이 ared 또는 호출됩니다.

시제품 없이 함수를 호출하는 것은 컴파일러가 올바른 파라미터의 수와 유형을 올바른 순서로 전달했는지 확인할 수 없기 때문에 안전하지 않습니다.콜이 실제로 올바르지 않은 경우 정의되지 않은 동작이 발생합니다.

파라미터 없는 함수를 올바르게 선언하고 정의하는 방법은 다음과 같습니다.

// Modern declaration of a parameterless function.
int qux(void);  // "void" as a parameter type means there are no parameters.
                // Without using "void", this would be a K&R declaration.

// Modern definition of a parameterless function
int qux(void)
{
    // ...
    return 0;
}

의 K에서 K&R을 합니다.int가치도 필요 없습니다.

심플한 HelloWorld 프로그램의 최신 C11 표기법에 대해 생각해 보겠습니다.

int main(int argc, char **argv) {
    printf("hello world\n");
    return 0;
}

이것은 K&R 표기 스타일과 동일합니다.

main(argc, argv)
int argc;
char **argv;
{
 printf("hello world\n");
 return 0;
}

에 주의:int 전에main()무시되지만 코드는 여전히 컴파일됩니다.K&R을 사용하다

인용: Wikipedia:

C의 초기 버전에서는 함수의 정의 전에 int 이외의 값을 반환한 함수만 사용했을 경우 선언할 필요가 있었습니다.이전 선언 없이 사용된 함수는 값이 사용되었을 경우 타입 int를 반환하는 것으로 간주되었습니다.

-- 출처 : https://en.wikipedia.org/wiki/C_(programming_language)#K.26R_C

이것은 레거시 코딩 스타일이며 명확성 문제로 인해 피해야 하지만 오래된 알고리즘 교과서는 이러한 종류의 K&R 스타일을 선호합니다.

언급URL : https://stackoverflow.com/questions/3092006/function-declaration-kr-vs-ansi

반응형