Using variables - c

I have a problem with this simple program because it doesnt give me the true outcome. I just want to sum two arguments in the first function and then use the outcome in the second one. It will be nice to have overall outcome in the main function. Also I would like to ask the same question with arrays.
#include <stdio.h>
#include <stdlib.h>
int sum()
{
int a=2;
int b=3;
int s=a+b;
printf("sum=%d\n",s);
return s;
}
int sum2(int s)
{
int c=5;
int d=c+s;
}
int main(int s,int d)
{
sum();
printf("sum=%d\n",s);
printf("sum2=%d\n",d);
getchar();
return 0;
}

There are many problems with this code:
int main(int s, int d) won't do what you think. Command-line arguments to your program come in string format. So you would need to use int main(int argc, char *argv[]).
The variables s and d in main() are completely independent to the variables in sum() and sum2(). So changing their values in those functions will not affect the original variables.
You're not even calling the second function!
You can do things like this:
int sum(int a, int b)
{
return a+b;
}
int sum2(int c)
{
return c+5;
}
int main(void)
{
int x = 2;
int y = 3;
int z = sum(x,y);
int w = sum2(z);
printf("z = %d\n", z);
printf("w = %d\n", w);
}

First of all, s is a local variable inside sum( ). Hence it cannot be available outside the function.
int sum() {
// ..
int s = a+b; // local variable, hence local scope
// ..
}
Also, secondly, int main(int s,int d) won't work since in command line arguments come in String format. So can't use a int there

I won't tell you the answer (lol but others have) but I'll give you these clues to figuring it out.
Ask your self which functions are returning data and which ones aren't.
Clue: the function needs a return to return some data.
Then ask yourself which functions' returns are actually being used.
Clue: to collect the data returned from a function you need to assign the result to a variable like so
int i;
i = somefunct();

You can't access the value of variable 's' outside the function sum() since it is out of scope. You'll have to return the value to your main() function. Also your main function parameters are incorrect. You need something more like this:
#include <stdio.h>
#include <stdlib.h>
int sum(int a, int b)
{
int s=a+b;
printf("sum=%d\n",s);
return s;
}
int sum2(int c, int sum)
{
return c+sum;
}
int main(int argc, char *argv[])
{
int val1 = sum(2, 3);
printf("sum=%d\n",val1);
int val2 = sum2(5, val1);
printf("sum2=%d\n", val2);
getchar();
return 0;
}

Related

Trying to have a function return a simple number, it returns something else

I'm discovering this language and code in general. I'm trying to understand how fuction return numbers. My goal is to have a function do an easy calculation and return the result, then display the result through the printf function.
Here's what I tried :
#include <stdio.h>
#include <stdlib.h>
int test1(int number1);
int main(int argc, char* argv[])
{
int number1 = 2;
test1(number1);
printf("%d\n", test1);
return 0;
}
int test1(int number1)
{
number1 += 2;
printf("%d\n", number1);
return number1;
}
It runs, and displays this :
4
14226428
I can't figure out why. The displayed 4 show that test1 runs and calculate correctly, but for some reason it returns something that it shouldn't. I suspect it's an adress but I can't find a way to make it return the value I'm looking for.
I managed to do it with a void function, as follows :
#include <stdio.h>
#include <stdlib.h>
void test1(int *number1);
int main(int argc, char* argv[])
{
int number1 = 2;
test1(&number1);
printf("%d\n", number1);
return 0;
}
void test1(int *number1)
{
*number1 += 2;
}
When this runs it displays a 4 as expected, yet I don't understand why it doesn't work with my int function. Could someone try to explain me slowly why it does that ? Thank you \o/
your first implementation is fine, your test function is doing its job (manipulating the value and returning the updated value), but you are not printing the returned value from the function.
You have called the function as test(number1), but haven't saved the returned value anywhere.
for example, the correct code would look like this:
int main(int argc, char* argv[]){
int number1 = 2;
int result = test1(number1);
printf("%d\n", result);
return 0;
}
OR
If you don't want to save the value in a variable you can just directly call the function
int main(int argc, char* argv[]){
int number1 = 2;
printf("%d\n", test1(number1));
return 0;
}
Remember, to call a function () parentheses are important.

What is this macro #define type_string(name) { #name , name }

Let's do the first example as simple as possible.
I want to know how to apply this macro; like here apply in e.g. printf("%s",macro(arg));
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
#define type_string(name) { #name , name }
int main(void) {
char *hi = "Hello";
char *arr[]=type_string(hi);
printf("%s\n",type_string(hi));
return 0;
}
Also what could be other methods for printing the function' names:
My last solution is this one:
Is there a better way to optimize this code, like tweaking around __func__?
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
// let's declare different functions for calculation
int add(int x, int y);
int sub(int x, int y);
int mul(int x, int y);
int divide(int x, int y);
// let's declare function pointers to different behaviors
//int (*functionPtr_1[4])(int,int); // basic form
typedef int (*myFuncDef)(int, int); // typedef as the basic form
int do_calculations (int (*functionPtr)(int, int)); // function receives function pointer with two args and returns int
int (*functionFactory(int n))(int, int);
int main() {
int m = 6;
int n = 10;
int res,i;
int (*functionPtr_arr[4])(int,int) = {&add, &sub, &mul, &divide};
for(i=0;i<4;i++)
{
res=(*functionPtr_arr[i])(4,5);
}
}
int add(int x, int y) {
int result = x + y;
printf("result for %s op is %d\n",__func__,result);
return result;
}
int sub(int x, int y) {
int result = x - y;
printf("result for %s op is %d\n",__func__,result);
return result;
}
int mul(int x, int y) {
int result = x * y;
printf("result for %s op is %d\n",__func__,result);
return result;
}
int divide(int x, int y) {
int result = x / y;
printf("result for %s op is %d\n",__func__,result);
return result;
}
#define FN_RECORD(f) { #f, f }
This macro works by taking a variable in, f, and putting that value into what it is replacing.
Ex.
Having a function int abc(void);
Putting FN_RECORD(abc) into your code will be replaced with { "abc", abc } after pre-processing. The # creates a string.
It appears that the person who created this macro intended it to be used as the name of a function as a c-string, along with it's function pointer.
The comment describing the macro is remarkably clear, so it is not certain what you might be confused by.
In context it is used to generate initialisers for the fns array. So:
fn_record fns[3] = {
FN_RECORD(fna),
FN_RECORD(fnb),
FN_RECORD(fnc)
};
Expands to:
fn_record fns[3] = {
{"fna", fna},
{"fnb", fnb},
{"fnc", fnc}
};
The comment says it is to save you typing, but that is a rather silly reason - its hardly a valuable time-saving. What it does usefully do is ensure that the string and the function name match to avoid possible errors.
Let's break it down one step at a time.
#define type_string(name) { #name , name }
int main(void) {
char *hi = "Hello";
char *arr[]=type_string(hi);
printf("%s\n",type_string(hi));
}
Compilation happens in two stages (three, if you count linking, but let's ignore that). The preprocessor and compiler are actually separate programs in a lot of cases, but the compiler runs the preprocessor automatically.
Preprocessing
First, we do all preprocessing. So let's look at what happens then:
char *arr[]=type_string(hi);
The token hi is passed to type_string. The fact that hi is a variable doesn't matter; name contains hi, not "Hello".
# is the stringification operator. Since name is hi, #name evaluates to "hi".
name just evaluates to hi.
So type_string(hi) as a whole evaluates to { "hi" , hi }, and the line as a whole becomes char *arr[]={ "hi" , hi };. printf("%s\n", type_string(hi)); works the same way, and becomes printf("%s\n", { "hi" , hi });.
Compiling
Now that preprocessing is done, the actual compiler gets to go. This is what the compiler will see:
int main(void) {
char *hi = "Hello";
char *arr[]={ "hi" , hi };
printf("%s\n",{ "hi" , hi });
}
{ "hi", hi } will evaluate to an array of char*; the first element implicitly points to the (constant) string literal "hi", and the second element initialized to the address currently contained in hi, which happens to be the address of the string literal "Hello".
Naturally, this won't work; printf("%s\n", { "hi" , hi }) is expecting a string and gets an array literal, which isn't legal in that context.
You could instead do printf("%s, %s\n", arr[0], arr[1]);, which would print hi, Hello.

C Program Compile Error: Undefined reference to function 'compare'?

Here is my code:
#include <stdio.h>
#include <stdlib.h>
int compare(int a, int b);
main()
{
int x,y;
x = 2, y = 1;
printf("%d", compare(x,y));
int compare(int a, int b)
{
int returnValue = 0;
if(a>b)
returnValue = 1;
else if(a<b)
returnValue = -1;
else
returnValue = 0;
return(returnValue);
}
}
And this is the compiler error that I recieve:
In function `main':
asdf.c:(.text+0x21): undefined reference to `compare'
collect2: error: ld returned 1 exit status
I have looked into this problem, and every question that I can find with this error is because people are importing functions from different files. These two functions are in the same file, and the compare() function is declared before the main(). I would appreciate any help as to why I am getting this error.
Thank you for your time.
You must define function outside the main function.
your code should be:
#include <stdio.h>
#include <stdlib.h>
int compare(int a, int b);
main()
{
int x,y;
x = 2, y = 1;
printf("%d", compare(x,y));
}
int compare(int a, int b)
{
int returnValue = 0;
if(a>b)
returnValue = 1;
else if(a<b)
returnValue = -1;
else
returnValue = 0;
return(returnValue);
}
The function compare must be out side the main program. Either you define the function header before the main() and have the function after the main or have the function before the main().
#include <stdio.h>
#include <stdlib.h>
int compare(int a, int b);
main()
{
int x,y;
x = 2, y = 1;
printf("%d", compare(x,y));
}
int compare(int a, int b)
{
int returnValue = 0;
if(a>b)
returnValue = 1;
else if(a<b)
returnValue = -1;
else
returnValue = 0;
return returnValue;
}
Nested function does not exist in C. But again speaking that it's a compiler specific
You can see gcc extension for nested function which is nonstandard.
So for solution simply move your function definition to outside the main.
You've declared the global function compare at file scope, but only defined a nested function main::compare. As commenters have pointed out, this is not standard C, it's a gcc extension that you don't want to be using.
Move compare out to file scope:
int main()
{
// do stuff
return 0;
}
int compare(int a, int b)
{
// do stuff
return value;
}
Put compare function out of main function. C language doesn't allow functions defined inside other functions.
Code
#include <stdio.h>
#include <stdlib.h>
int compare(int a, int b);
int main(void )
{
int x,y;
x = 2, y = 1;
printf("%d\n", compare(x,y));
}
int compare(int a, int b)
{
return ((a<b) - (a>b));
}
You have two different functions compare: One at global scope, which is only declared, but not defined, and one defined at local scope. The local compare can only be called from local scope, but only after it is defined. (Declaring a nested function inside the body of main before its definition doesn't work, because the C standard permits declarations in function bodies, but treats them as global.)
If you must use nested functions, move the definition of your local compare to the beginning of main. Nested functions are non-standard.
It is better to move the definition of compare outside the function into file scope. If you keep the definition of compare close to where it's called and make it static, you will get the same behaviour.

Problem with simple function in C

I am new in C and I have problem with compiling this code.
#include <stdio.h>
void suma( int a, int b, int wynik)
{
wynik=0;
printf("a=\n");
scanf("%d",&a);
printf("b=\n");
scanf("%d",&b);
wynik=a+b;
printf("wynik = %d",&wynik);
}
int main()
{
suma(int a, int b, int wynik);
}
I don't know why but compiler tells me that 2 argument has type int * insted of int. I dont' know what does it mean and where I made mistake.
Change
printf("wynik = %d",&wynik);
to
printf("wynik = %d",wynik);
Otherwise you'll be printing the address of wynik as an integer.
Also the way you call suma makes no sense.
change printf("wynik = %d",&wynik); to printf("wynik = %d",wynik);
and also you don't seem to need the arguments of suma.
Try this:
void suma()
{
int a,b,wynik;
wynik=0;
printf("a=\n");
scanf("%d",&a);
printf("b=\n");
scanf("%d",&b);
wynik=a+b;
printf("wynik = %d",wynik);
}
int main()
{
suma();
}

What does "implicit declaration of function" mean?

#include <stdio.h>
int main()
{
int a = 4;
int b = 3;
addNumbers(a, b);
}
int addNumbers(int a, int b)
{
return a + b;
}
Why does this not compile, I get a message saying implicit declaration of function addNumbers()?
Either define the function before main() or provide its prototype before main().
So either do this:
#include <stdio.h>
int addNumbers(int a, int b)
{ //definition
}
int main()
{ //Code in main
addNumbers(a, b);
}
or this:
#include <stdio.h>
int addNumbers(int, int);
int main()
{ //Code in main
addNumbers(a, b);
}
int addNumbers(int a, int b)
{ // definition
}
You need to declare the function before you call it in main(). Either move it before main or at least declare it there.
Also, you should prob add return 0 at the end of the main function since it's supposed to return int.
#include <stdio.h>
int addNumbers(int a, int b)
{
return a + b;
}
int main()
{
int a = 4;
int b = 3;
addNumbers(a, b);
return 0;
}
You have to either move the entire addNumber() function above main or provide a prototype. The latter is done the following way:
int addNumbers(int a, int b);
int main()
{
// code of main() here
}
int addNumbers(int a, int b)
{
//code of addNumbers() here
}
Put addNumbers before main
int addNumbers(int a, int b)
{
return a + b;
}
int main()
{
int a = 4;
int b = 3;
addNumbers(a, b);
}
UPDATE:
To print it, printf("%i",addNumbers(a, b)); will display 7 in above case.
You can move the whole function above the point where it is called, or use a function prototype, like this:
#include <stdio.h>
int addNumbers(int a, int b); // function prototype
int main()
{
int a = 4;
int b = 3;
addNumbers(a, b);
}
int addNumbers(int a, int b)
{
return a + b;
}
You'll need a forward declaration of the addNumbers function or its definition moved up before the first usage:
// 2161304
#include <stdio.h>
// forward declaration
int addNumbers(int a, int b);
int main()
{
int a = 4;
int b = 3;
addNumbers(a, b);
}
// alternatively move this up before main ...
int addNumbers(int a, int b)
{
return a + b;
}
Regarding main and return:
Programs will compile without. The signatures of main defined by the standard are:
int main(void)
int main(int argc, char **argv)
There are three portable return values:
0, EXIT_SUCCESS, EXIT_FAILURE
which are defined in stdlib.h.
Declare the function before using it by either adding a prototype before main():
int addNumbers(int a, int b);
or move the whole addNumbers function before main().
I agree with declaration and definition thing but i am not getting any compilation errors with the above code.My gcc version is "4.4.1-4ubuntu9".Any ideas.
I have done a little modification to test the code.
#include <stdio.h>
int main()
{
int a = 4;
int b = 3;
printf("%d", addNumbers(a, b)); // Printf added.
}
int addNumbers(int a, int b)
{
return a + b;
}
You must declare the function before using.
Remember these 4 basic parts while dealing with functions.
Declaration
Call
Definition
Return
if your compiler is C99 standard it throws and error "implicit declaration", since since default promotion is obsolete in C99 standard.
if you try to compile with C89 standard this would be allowable.
In C99 standard function prototype is necessary
Since the compiler executes one line after another,by the time it sees the function call,it has to have the information about that function which the main function is calling.so my friend u need to tell the compiler about the function before you can ever use it.

Resources