i have a program like this one: #include<stdio.h> void sum(int a,int b, int s){ s=a+b;} int main(){ int s; suma(2,3,s); printf("Sum is %d\n",s); return 0;} Code (markup): the error is in function main as it says i m using 's' - uninitialized variable. i need to initialize the variable s with s=0; but i don't know where to insert this line. any help would be appreciated. thanks
Are you trying to learn to program in C? How did you get that far without knowing how to do this? In your main function, just add 's=0;' after 'int s;'.
man, that's the first thing i tried, but it didn't work. it shows the sum being equal to 0, meaning the function is not taking any action on s. that's why i posted that.
You can either do this: #include <stdio.h> int sum(int a, int b) { return a+b; } int main(){ int s = 0; s = sum(2,3); printf("Sum is %d\n",s); return 0; } Code (markup): or this (but this is as C++ now because of the use of reference).. #include <stdio.h> void sum(int a, int b, int& s) { s = a+b; } int main(){ int s = 0; sum(2,3,s); printf("Sum is %d\n",s); return 0; } Code (markup):
Your request was how to resolve the warning about s being uninitialized, not that you were getting the wrong answer. @rainuff solves the second part.
your function is a pass by value function, and it's a non-return type, it does not change anything to the variable, you have to pass by referrence, or pass by pointer, use & before the variable in the function header like this: void sum(int a, int b, int &s), and the function in your main function I see it's suma(2,3,s), I duno whether you type wrong in here, or in your computer, so one way is that you can make a return type, like int sum(int a, int b, int s){s = a+b; return s;} int main() { int s; s = sum(2, 3, s); printf("sum is %d\n“, s); return 0; } and another way is: void sum(int a, int b, int &s) {s = a+b;} int main() { int s; s = 0; sum(2, 3, s); printf("Sum is %d\n", s); return 0; } good luck with that!