C编程哪个更好,哪个更喜欢请解释 [英] C programming which is better and which one to prefer please explain

查看:56
本文介绍了C编程哪个更好,哪个更喜欢请解释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<stdio.h>
int add(int,int);
int main()
{
	int first,second,sum;
	printf("Enter your first number : ");
	scanf("%d",&first);
	printf("Enter your second number : ");
	scanf("%d",&second);
	printf("sum = %d ",add(first,second));
}
int add(int x,int y)
{
	int sum;
	sum=x+y;
	return sum;
}









OR

#include<stdio.h>
void add()
int main()
{
	add();
}
void add()
{
int first,second,sum;
printf("Enter your first number : ");
scanf("%d",&first);
printf("Enter your second number : ");
scanf("%d",&second);
sum=first+second;
printf("sum =%d",sum);
}





我的尝试:



两者都给出了正确的答案但更喜欢哪一个请解释



What I have tried:

Both gives right answer but which one to prefer please explain

推荐答案

说实话,这是风格问题 - 第二个版本更好对于更大的函数,但对于一个简单的代码行,我更喜欢第一行。



好​​吧,编译器可能会内联代码 - 它们是这些天非常聪明 - 所以不会有性能开销,但编写一个函数来添加两个数字有点超过顶部! :笑:



我要做的是编写一个函数,它会提示并取一个用户inptu并返回它:

To be honest, it's a matter of style - and the second version is better for "larger" functions, but for a single trivial line of code I'd prefer the first.

OK, the compiler will probably inline the code anyway - they are pretty clever these days - so there won't be a performance overhead, but writing a function to add two numbers is a bit over the top! :laugh:

What I would do is write a function that takes a prompt and fetches a user inptu and returns it:
int GetInt(const char *prompt)
    {
    int result;
    printf(prompt);
    scanf("%d", &result);
    return result);
    }

然后使用两次:

And then use that twice:

int main()
    {
    int first,second,sum;
    first = GetInt("Enter your first number : ");
    second = GetInt("Enter your second number : ");
    printf("sum = %d\n", first + second));
    }


这一个:

This one:
#include<stdio.h>
int main()
{
  int first,second;
  printf("Enter your first number : ");
  scanf("%d",&first);
  printf("Enter your second number : ");
  scanf("%d",&second);
  printf("sum = %d\n", (first + second));
  return 0;
}


引用:

C编程哪个更好请更喜欢请解释

C programming which is better and which one to prefer please explain



对此没有明确的答案,这是一个品味问题。

我本可以写两个,对于这样的一个小项目,没有区别。

如果 add 将被重用于不同的东西,首先是样式。


There is no definitive answer to this, it is a matter of taste.
I could have written both, for such a small project, there no difference.
if add is to be reused for different things, first style is preferable.


这篇关于C编程哪个更好,哪个更喜欢请解释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆