Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

87
Views
Reusing variable in function parameter list
int doSomething(int n, int arr[n])

What confuses me here is the reusing of the n variable inside the parameter list. Can anyone explain why this is valid and what are the use cases?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

C allows several syntaxs for passing an array pointer including:

 int* arr, int arr[] or int arr[10]  

However ALL of these are equivalent to the first - that is the compiler sees only an int pointer and does not use any size that may have been specified in the array square brackets to enforce integrity on the size of the array passed. In all the above cases the compiler will generate:

void __cdecl foo(int * const)

The only way to specify the size of an array is, as you have done, pass a separate parameter indicating the size/length of the array.
In the example you cite the n in arr[n] is not used by the compiler to maintain any integrity on the array bounds - in the example it is only included as an indication that the first parameter is the size. A less controversial form of the same code might be just to state that more explicitly:

int doSomething(int arr_len, int arr[])

In terms of what is the best convention or preference for passing an pointer and its array size see this question.

over 4 years ago · Santiago Trujillo Report

0

It is valid.

For this specific case it is equivalent to:

int doSomething(int n, int arr[]);
int doSomething(int n, int *arr);

because the array parameters are automatically transformed into pointers to arrays' elements. In general there are a few differences between array-like and pointer declarations of parameters. See link for more details.

IMO, the better usage should be:

int doSomething(int n, int arr[static n]);

This static n tell the compilers that at least n elements pointer by arr are valid. Moreover it makes the declaration visually different from a declaration of array what helps to avoid surprising issues when sizeof arr is used.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!