developer tip

주 함수에서 argc와 argv의 이름을 바꾸는 것이 안전합니까?

copycodes 2020. 9. 23. 07:45
반응형

주 함수에서 argc와 argv의 이름을 바꾸는 것이 안전합니까?


많은 프로그램에서 여러 인수와 문자열 배열에 표준 이름을 사용합니다. 주 함수의 프로토 타입은 다음과 같습니다 int main(int argc, char *argv[]);.. 그러나 이러한 변수에 대해 사용자 지정 이름을 선택하면 뭔가 깨질까요?

int main(int n_of_args, char *args[]);

컴파일러의 맥락에서 모든 것이 정상입니다. 이러한 변수는 주 함수에 대해 지역적이므로 이름이있을 수 있습니다. 그리고 간단한 코드가 완벽하게 빌드되고 실행됩니다. 그러나 이러한 이름은 전처리기에 의해 사용될 수 있습니다. 그렇다면 이러한 인수의 이름을 바꾸는 것이 안전합니까?

추신 개인적으로 나는이 이름이 매우 비슷하고 한 글자 만 다르기 때문에 나쁘다고 생각합니다. 그러나 모든 사람들은 어떤 이유로 든 그것들을 사용합니다.


예, 유효한 변수 이름을 사용하는 한 안전합니다. 그들은 지역 변수이므로 범위가 main기능을 넘어 가지 않습니다 .

C 표준 의 섹션 5.1.2.2.1에서 :

프로그램 시작시 호출되는 함수의 이름은 main. 구현은이 함수에 대한 프로토 타입을 선언하지 않습니다. 반환 유형 int과 매개 변수없이 정의되어야합니다 .

int main(void) { /*  ... */ }

또는 두 개의 파라미터들 (여기로 언급 argc하고 argv, 어떤 이름이 사용될 수있다하더라도, 그들은 선언 된 함수에 국부적으로 )

int main(int argc, char *argv[]) { /* ...   */ }

또는 동등한 것; 또는 다른 구현 정의 방식으로

즉, argc이외의 다른 것을 argv사용하면 이러한 매개 변수의 일반적인 이름에 익숙한 코드를 읽는 다른 사람들이 혼동을 일으킬 수 있습니다. 명확성의 측면에서 실수하는 것이 좋습니다.


이름 argc과는 argv실제로 C ++ 표준 이전의 C에 ++ (11)에 의해 위임되었다. 다음과 같이 명시되어 있습니다.

모든 구현은 main에 대한 다음 정의를 모두 허용해야합니다.

int main ()

int main ( int argc , char * argv [])

과에 대한 요구 사항을 논의하기 위해에 갔다 argcargv.

따라서 기술적으로 다른 이름을 사용하는 프로그램은 표준을 준수하지 않았으며 컴파일러는이를 거부 할 수있었습니다. 물론 실제로 그렇게 한 컴파일러는 없습니다. comp.std.c ++의이 스레드 또는 이 C ++ 03 초안 표준 의 섹션 3.6.1을 참조하십시오 .

이것은 거의 확실히 단순한 감독이었고 C ++ 11에서 변경되었습니다.

모든 구현은

  • () 반환 int
  • ( int, 포인터에 대한 포인터 char) 반환 의 함수int

main(8.3.5) 의 유형으로 . 후자의 형식에서는 설명을 위해 첫 번째 함수 매개 변수가 호출 argc되고 두 번째 함수 매개 변수가 호출됩니다 argv.


물론이 매개 변수의 이름 을 원하는대로 안전하게 바꿀 수 있습니다.

 int main(int wrzlbrnft, char* _42[]) {
 }

이름은 모래에 기록됩니다. 최종적으로 컴파일 된 코드에는 영향을 미치지 않습니다.


중요한 것은 선언과 정의의 매개 변수 유형이 실제로 일치한다는 것입니다.

main()함수 의 서명 은 본질적으로 다음과 같이 선언됩니다.

 int main(int, char*[]);

구현에서 실제로 사용해야하는 경우 이름을 지정해야합니다. 어떤 이름이 사용되는지는 앞에서 언급했듯이 실제로 관련이 없습니다.


예. 안전하고 이상해 보이지만 아무 것도 깨지지 않습니다.


예, 다른 이름을 사용하는 것이 안전합니다.

개인적으로 나는 그것을 추천하지 않을 것이다. 전통 argc적이고 argv널리 알려져 있고 당신의 코드로 작업 할 수있는 다른 모든 C 프로그래머에게 익숙하다. 장기적으로 자신 만의 특별하고 다른 이름을 사용하면 자신의 이름을 더 좋아하기 때문에 자신을 구할 수있는 것보다 독자들 사이에 훨씬 더 많은 혼란과 좌절감을 줄 것입니다.

"로마에있을 때 로마인처럼하십시오."


예, 원하는대로 이름을 바꿀 수 있습니다. 그것들은 단순히 함수 매개 변수 이름이며 그 이상은 아닙니다.


모두가 기술적 인 C ++ 규칙을 잘 다루었다고 생각합니다. 대답은 '예'입니다. 전통과이 특정 기능이 특별하고 상징적이라는 사실을 제쳐두고,이 기준에 따라 변하지 않을 유효한 포인트를 포함합니다.

종종 나는 선택의 철학이 거의 논의되지 않는다고 느낍니다. 그래서 이것이 시작하도록 요청 된 이유에 대해 중요하다고 느끼기 때문에이 문제에 대한 관점을 제공하고 싶었습니다.

이 질문은 일반적으로 코드에서 영어를 표현하는 선택을 포함합니다. 특히 짧은 손이 비슷한 모양의 텍스트를 표시하는 경우 짧은 손 설명에 신경 쓰이는 것 같습니다. 하지만 귀하의 예에서 argn을 n_of_args로 변경하면 한 가지 유형의 속기 만 실제 값 추가없이 다른 유형의 속기로 변경됩니다 : 설명 또는 기타 가시적 속성.

단어 '숫자'가 문자 'n'으로 대체되었습니다.

짧은 손 방지 철학을 통해 짧은 손 이름을 변경하는 경우 다음과 같은 것이 더 적절 해 보일 수 있습니다.

main (int argumentCount, char ** argumentVector)

저는 항상 두 가지에 대해 생각합니다. 이름을 지정하는 것은 무엇인지 및 / 또는 묵시적인 용도로 지정하는 것입니다. 벡터라는 속성이 이중 간접 **에 의해 암시되기 때문에 그것을 argumentVector라고 부르는 것은 나에게 중복됩니다. 따라서 코드를 작성하는 방법에 대한 더 나은 긴 손은 ** 인수입니다.

어떤 사람들은 argumentCount라는 변수가 int로 선언되고 Count는 음수가 될 수 없지만 음수 int {unsigned is better}를 가질 수 있다고 말합니다.

Again, what it is and how it is used comes to play in this interpretation. If it is a Count, then I would assume it would never be negative. After all, how can you have a Count of -2 apples. I would say, you OWE two apples. If it is a Number, then I would expect a negative case to be possible. This is why the additional word 'of' is likely important to you. That, and perhaps a number as referred to by a collection implies a specific item rather than a property of the collection itself. Ie: argumentsNumber = 5 implies a specific argument but not numberOfArguments.

main( int maxArgumentsIndex, char ** arguments ).

This removes ambiguity. Calling it an index removes negative case ambiguity and also describes what it is, and additionaly how to use it. It also implies by the english wording that a max is an absolute and would feel weird writing code that modifies this value (it should be const). 'arguments' makes sense here since it is plural, describes what it is, and how it should be used already. Even interpreting this way can be dangerous as an Index is -1 of a Count/NumberOf. 5 arguments yields a maxIndex of 4!!

Any other function and I would completely use:

void function( const unsigned int maxArgumentsIndex, const char ** arguments )

Not all situations merit long hand descriptors. In fact, some times a short hand yields more readability, in particular, in the case of writing math classes such as a Vec3f, Matrix, Quaternion, etc... I will almost always try to match the math language rather than the linguistic one. float x, y, z vrs. float xComponent and the like.

I understand all of this is a style choice, but being conscious of the choices will really help in the long run. I guarantee seasoned programmers get bothered when arrays are not written in plural form, but then again, main is a special prose of existence ;)


As per C Standards, Yes you can rename, Nothing going to impact. As i understood, in C Language, the default Keyword/types/token names were defined with purpose/usage, so in the same way it is defined names

argc --> argument count

argv --> argument vector

which is also make sense in terms of usage, So you can change to any name expect Reserved names

In GCC, the program execution start with the function name main it doesn't depends on his parameters.

When you write standalone program for micro controllers, you no need to bother about the name main instead you can define your own name and change the Assembly entry_point to point your function. It depends on controller compiler and availability of pre-define controller source code. I've did this in Freescale controller under Code-warrior.

My Note:

It's better to follow the common standards/code style to make code more visible and readable


It is safe as far as the compiler is concerned.

The only problem this can cause is confusion. People who read your code will expect those two variables to have their standard names. You could even do something like this:

int main(int foo, char ** bar)
{
    int argc;
    float argv;

But I don't think I need to tell how bad practice this would be.


If you don't like the variable names, why not substituting them with the macro #define :

#define yourCounterName argc
#define yourVectorName  argv 

You will not take any risk and produce a "clean solution".

참고URL : https://stackoverflow.com/questions/36945552/is-it-safe-to-rename-argc-and-argv-in-main-function

반응형