Very simple question

P

Paminu

I am trying to refresh my C skills and have therefore writtin this little
program:

#include <stdio.h>

int sum (int a, int b)
{

printf(a+b);
return a+b;
}


int main()
{
sum(1,2);

}

But when I compile I get :

test.c: In function `sum':
test.c:5: warning: passing arg 1 of `printf' makes pointer from integer
without a cast

me@ubuntu:~/opgaver$ ./test
Segmentation fault


What am I missing?
 
R

Richard Heathfield

Paminu said:
I am trying to refresh my C skills and have therefore writtin this little
program:

#include <stdio.h>

int sum (int a, int b)
{

printf(a+b);

printf("The sum is %d\n", a + b);
 
R

Randy Howard

Paminu wrote
(in article said:
I am trying to refresh my C skills and have therefore writtin this little
program:

#include <stdio.h>

int sum (int a, int b)
{

printf(a+b);

$ man 3 printf

<or look it up in whatever documentation is appropriate for your
compiler and library configuration>
 
M

Mike Wahler

Paminu said:
I am trying to refresh my C skills and have therefore writtin this little
program:

#include <stdio.h>

int sum (int a, int b)
{

printf(a+b);
return a+b;
}


int main()
{
sum(1,2);

}

But when I compile I get :

test.c: In function `sum':
test.c:5: warning: passing arg 1 of `printf' makes pointer from integer
without a cast

me@ubuntu:~/opgaver$ ./test
Segmentation fault


What am I missing?

You forgot to read the documentation for 'printf()' or
a textbook which explains how to use it.

printf("%d\n", a + b);

"Style" note: Your function is named 'sum()'. So that's what it
should do. Nothing else. Output doesn't belong in it. It limits
the function's usability. What if I want to call 'sum()' several
times as part of other computation, and only want output of the
final result?

#include <stdio.h>

int sum(int a, int b)
{
return a + b;
}

int main(void)
{
int i = 5;
int j = sum(i, 3); /* your way would give unwanted output here */
printf("%d\n", sum(j, 2));
return 0;
}

-Mike
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,206
Latest member
SybilSchil

Latest Threads

Top