简体   繁体   English

良好的作法:C变量

[英]Good style practice: C variables

Could I get people's opinions on naming variables when passed to functions? 传递给函数时,能否获得人们对命名变量的意见? I've looked at a few guides but can't see anything specific on this. 我看过一些指南,但是看不到任何具体的内容。

I'm passing a variable to a function and for clarity (I hope), I'm giving it the same name in main as in the function. 我正在将变量传递给函数,为了清楚起见(希望如此),我给它的名称与函数中的名称相同。 I know they are not the same variable (just passed by value), but they represent the same thing; 我知道它们不是相同的变量(只是通过值传递),但是它们表示相同的事物。 is there a reason to change their name that is more important than the complexity it would add? 有没有理由更改其名称比添加名称更重要?

Example, I have been using: 例如,我一直在使用:

main(){

int cakes, cost, total;
cakes = 2;
cost = 11;

total = sum(cakes, cost);
printf("The total cost for %d cakes is '%d'.\n", cakes, total);

return 0;
}

int sum(int cakes, int cost){
  int total;
  total = cakes * cost;

  return total;
}

Should I be using eg fcakes , fcost , ftotal in the function, and if so why? 我应该使用如fcakesfcostftotal的功能,如果是这样,为什么?

Cheers, 干杯,

W w ^

If you want to use your Sum function for something else than cakes, naming might be important. 如果您想将Sum函数用于蛋糕之外的其他事物,则命名可能很重要。

main(){

    int cakes, bananas, apples, cost, bananascost, applecost, total;
    cakes = 2;
    bananas = 42;
    apples = 69;
    cost = 11;
    bananascost = 5;
    applecost = 12;

    total = sum(cakes, cost);
    printf("The total cost for %d cakes is '%d'.\n", cakes, total);
    total = sum(bananas, bananascost);
    printf("The total cost for %d bananas is '%d'.\n", bananas, total);
    total = sum(apples, applecost);
    printf("The total cost for %d apples is '%d'.\n", apples, total);
    return 0;
}

int sum(int number1, int number2){
    int result;
    result = number1 * number2;
    return result;
}

It is not a bad idea, but I think the problem is more related to the design. 这不是一个坏主意,但我认为问题更多与设计有关。 For instance, sum function is to sum (or whatever), instead of adding just cakes and cost. 例如,求和函数是求和(或其他任何东西),而不是仅仅增加蛋糕和成本。 Doing a function as generic as possible (even to be easily used in another project) solves this kind of problems. 做一个尽可能通用的功能(甚至可以很容易地在另一个项目中使用)可以解决这类问题。

If you use the same name in main and in sum you have got two different variables with different scope with the same name. 如果您在mainsum使用相同的名称,则您将获得两个具有不同范围,具有相同名称的不同变量。 That could be difficult to debug. 那可能很难调试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM