-5

So, for my first C project I wanted to start simple with a calculator, but all the function SUM does is return 0.00000.

#include <stdio.h>

int SUM (float n1, float n2);

int main() {
    float num1 = 0; 
    float num2 = 0;
    float res = 0;
    scanf("Enter 2 numbers: %f %f", &num1, &num2);
    res = SUM(num1, num2);
    printf ("%f", res);
}

int SUM (float n1, float n2) {
    float sum = n1+n2;
    return &sum;
}
GSerg
  • 76,472
  • 17
  • 159
  • 346

1 Answers1

7

You declared that the SUM function will return an integer value (int).

Then you added two floats together, and returned the address of the result.

The address of a float is nothing like the value of an int.

You have invoked Undefined Behavior.


float SUM (float n1, float n2);   // SUM should return a float.


float SUM (float n1, float n2) {
    float sum = n1+n2;
    return sum;                   // Return the sum (without any addresses)
}

P.S.

You have a function named SUM (with capital letters), and a variable named sum with lowercase letters. While this is technically OK, it may be a point of confusion if another programmer reads your code. Can you always be sure of the difference between Sum, sum, SUM? What about Sine, sine, sin, Sin, SINE, etc.?

You should put in extra effort to name your functions, variables, constants, etc clearly and unambiguously so that understanding and using the proper one in the proper context is easy for all programmers.

abelenky
  • 63,815
  • 23
  • 109
  • 159
  • 1
    @TobySpeight: Edit rejected. C absolutely does have *addresses*; C lacks *references*. – abelenky Dec 06 '19 at 13:01
  • There are a few passing mentions of addresses in the C standard, but there's no *address* type. What we're talking about here is a *pointer* (which includes the type of the pointed-to object). Re-read your copy of the standard if you're not convinced. – Toby Speight Dec 06 '19 at 14:06
  • @TobySpeight *There are a few passing mentions* "[F]ew" is 79 in [the last draft of the C11 standard](https://port70.net/~nsz/c/c11/n1570.html), at least by the number on my browser search bar. Along with 11 instances of the exact phrase "address of". – Andrew Henle Dec 06 '19 at 15:42
  • 1
    (cont) And [**6.5.3.2 Address and indirection operators**](https://port70.net/~nsz/c/c11/n1570.html) states "1 The operand of the unary `&` operator shall be either a function designator, the result of a `[]` or unary `*` operator, or an lvalue that designates an object that is not a bit-field and is not declared with the register storage-class specifier. 2 The operand of the unary `*` operator shall have pointer type. Semantics 3 The unary `&` operator yields the address of its operand. ..." The `&` operator yields an address that is a pointer type. Pointers **are** the C "address type" – Andrew Henle Dec 06 '19 at 15:45
  • @Andrew, that's exactly what I was getting at. C uses pointers to implement addressing. – Toby Speight Dec 09 '19 at 08:49