0

In this code I seem to get zero, I'm not too familiar with as to why I can't change the variable length with the function I created. Any help could be useful.

 #include <stdio.h> double get_length(double a); int main(int argc, char* argv[]) { double length = 0; get_length(length); printf("%lf", length); return 0; } double get_length(double a) { printf("What is the rectangle's length?\n"); scanf("%lf", &a); return a; } 

When it prints it returns 0.0000

2
  • 4
    Works as intended: local variables/function arguments do not survive the function's return. Commented Oct 20, 2013 at 22:10
  • A common misunderstanding of functions in C. calling get_length(x); has no effect on value of x. Commented Oct 20, 2013 at 22:15

2 Answers 2

6

You're not storing the return value. Change:

get_length(length); 

to:

length = get_length(length); 

There's no need to pass length when you do this.

The other way to do it is to pass an address:

#include <stdio.h> void get_length(double * a); int main(int argc, char* argv[]) { double length = 0; get_length(&length); printf("%f", length); return 0; } void get_length(double * a) { printf("What is the rectangle's length?\n"); scanf("%lf", a); } 

Note that %f, not %lf, is the correct format specifier for a double in printf(). Using %lf is correct for scanf(), however.

Sign up to request clarification or add additional context in comments.

2 Comments

By the way, the original double get_length(double a) is kinda funny: it essentially asks the caller to initialize the function's local variable double a.
@Joker_vD: Yes, saves one single line of source code at the expense of much weirdness.
3

C is "pass-by-value", which means the value is actually copied in. So changing the value by using the reference doesn't actually change the original reference.

There are two ways around this:

1) store to a local value and then capture the return value:

length = get_length() ... double get_length() { double a; printf("What is the rectangle's length?\n"); scanf("%lf", &a); return a; } 

2) pass a pointer:

get_length(&length) ... double get_length(double *length) { printf("What is the rectangle's length?\n"); scanf("%lf", length); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.