Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

Suppose I'm writing a program in C in which several parameters are asked at the beginning of the execution to the user and then remain costant until the end. Now, I need to pass these parameters to some function.

Since they are unchanged through the program, my temptation would be to declare them as global variables, to have them visible to all functions. However, I see that this is not a good practice if the dimension of the program gets big (this has been asked and answered here).

However, I neither see the point of creating functions with, say, 6 arguments, when the variable ones are only 2. Is there a more elegant way to do this without compromising too much the manipulability of the code?

share|improve this question
    
(I don't know why but it doesn't let me change "SE"→"Hello, programmers.SE!" –  pppqqq Oct 9 '13 at 20:13

2 Answers 2

up vote 9 down vote accepted

If you are asking for several parameters at the beginning, and these parameters never change, and need to be passed together, use a struct:

struct options {
    bool isDebug;
    int numberOfDigits;
    char userName[40];
};

Then you don't have six arguments, where only two are variable, but rather just three:

doItNow(int speed, float precision, struct options* opts);

(Even if you decided to use globals, it would still be better to bundle them together like that.)

One big advantage to passing these options into the function is that it makes it clear to the caller that they are required by the function.

share|improve this answer

@Steven Burnap has outlined my preferred option. However, it often happens in large programs that one small function way down the call tree needs the information and it makes the code less readable and harder to maintain if you pass the data down the stack as parameters.
An alternate in C is make the data static within a module and provide one or more getter and setter function(s). The setter function should only be called at program initialization and this can easily be checked, and all references to the data can be quickly found by looking for calls to the getter. This is a common pattern for things like command line parameters and VSPs (Variable System Paramaters - data such as configuration items that does not change during program execution)

Debugging becomes easier as you can place trace outputs in the routines.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.