Search code examples
ccygwin

How do I declare variables when I'm prompting the user to enter them?


I'm trying to learn call functions and I've come across a problem where I'm being told I need I need to declare a, b, c, and d, but the point of the program is to prompt the user for these numbers and then sum them.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

int f(int a, int b, int c, int d); 
int g(int b, int c, int d);
int h(int c, int d);
int i(int d);

int
main(int argc,char **argv)
{
        int result;
        result = f(a,b,c,d);
        printf("Value of a?");
        scanf("%d",a);
        printf("Value of b?");
        scanf("%d",b);
        printf("Value of c?");
        scanf("%d",c);
        printf("Value of d?");
        scanf("%d",d);
        printf("Your result is %d",result);
        return 0;
}

int
f(int a, int b, int c, int d)
{
    return a + g(b,c,d);
}

int
g(int b, int c, int d)
{
        return b + h(c,d);
}

int
h(int c, int d)
{
        return c + i(d);
}

int
i(int d)
{
        return d + d;
}

The specific warning is

    call.c:16:13: error: ‘a’ undeclared (first use in this function)
      result = f(a,b,c,d);

and it repeats for b, c, and d.

Can anyone tell me what I've done wrong? I put the function signatures at the top where int a, int b, int c, and int d are already defined so I'm confused as to what I've done incorrectly.

Edit: Question has been solved! The code should look like

        int result;
        int a;
        int b;
        int c;
        int d;
        printf("Value of a?");
        scanf("%d",&a);
        printf("Value of b?");
        scanf("%d",&b);
        printf("Value of c?");
        scanf("%d",&c);
        printf("Value of d?");
        scanf("%d",&d);
        result = f(a,b,c,d);
        printf("Your result is %d",result);
        return 0;

Solution

  • You need to declare those variables in main, try changing your code to

    int result, a, b, c, d;

    Also scanf expects pointers in it's variadic portion of arguments, so you're going to need to use the & reference operator to take the address of a

    Example: scanf("%d", &a); And do this for all of your scanf calls.