Calling another function from printf?

2020-04-21 03:12发布

I am doing a simple challenge from a book on C/Objective-C where I have to write a program that computes and displays the square of an integer, while also putting the numbers in quotation marks.

I made a program that works successfully but I have two questions about it. Firstly having had the the idea of cutting back on the amount of code in mind, to practice being efficient and concise in my code, I called my squareOfInteger function from my printf statement. Is this advisable though? It worked but I'm worried this might be bad practice?

The other thing nagging at me is whether or not I need to reiterate the type as being an int inside the parameter of my function before my variable number, or whether it is enough to declare the result as being of type int, and leaving out type in the parameter, which I have done below.

Here is my code:

#include <stdio.h>

int squareOfInteger(number)
{
    int square = number * number;
    return square;



}

int main(int argc, const char * argv[]) {
    int myNumber = 5;
    printf("\"%d\" squared is \"%d\".\n", myNumber, squareOfInteger(myNumber));
    return 0;
}

I would greatly appreciate your help.

标签: c
2条回答
贪生不怕死
2楼-- · 2020-04-21 03:51

"I called my squareOfInteger function from my printf statement. Is this advisable though?"

There is nothing wrong in calling the function from within a function. It depends on case, where you say need to retain the squared value (as not in your case where you just need to print the value) and perform other operations on it. like:

int value = myFun(100);
int nextVal = myNextFun(value);

"The other thing nagging at me is whether or not I need to reiterate the type as being an int inside the parameter of my function before my variable number, or whether it is enough to declare the result as being of type int, and leaving out type in the parameter, which I have done below."

Yes you should use define the type of number (in your case as by default it would be integer type and would fail if you have it of other type) as a best practice as it will make code more clear and readable.

查看更多
叼着烟拽天下
3楼-- · 2020-04-21 03:57

I called my squareOfInteger function from my printf statement. Is this advisable though? It worked but I'm worried this might be bad practice?

Calling a function from printf() is not bad. But there might be scenarios leading to undefined behavior since the order of evaluation within printf() is not specified.For example:

int func(int *p)
{
   *p =30;
}
int main()
{
   printf("%d %d",num,func(&num));
   return 0;
}

Here you are calling func() as well as printing the value of num so you have UB.

whether it is enough to declare the result as being of type int, and leaving out type in the parameter

If the type of the argument is not specified then it defaults to int.But it is always good to mention the type of the arguments.

查看更多
登录 后发表回答