-1
typedef struct{
 int num, den;
} tfrac;

tfrac multf(tfrac a, tfrac b);

tfrac multf(tfrac a, tfrac b){
  tfrac res;
  res={a.num*b.num, a.den*b.den}; //The ERROR is here
  return res;
}

This program multiplies fractions. I don't know why I have an error in the function.

10
  • 4
    What is res={a.num*b.num, a.den*b.den}; supposed to do? It's certainly not valid C. Commented Dec 7, 2018 at 23:26
  • what datatype is res ? Commented Dec 7, 2018 at 23:26
  • @brokenfoot: tfrac. Commented Dec 7, 2018 at 23:27
  • 1
    What/who lead you to belive that typedefing a struct would be a good idea?, not a rhetorical question, I'm genuinely curious. Commented Dec 7, 2018 at 23:32
  • 3
    @JennyT-Type typedef'ing structs is very common and idiomatic in C. Why are you asking that question? Commented Dec 7, 2018 at 23:50

2 Answers 2

0

An initializer is a part of a declarator. So you can't declare your variable on one line and then assign values to it with an initializer on another line. Instead:

tfrac res={a.num*b.num, a.den*b.den};
Sign up to request clarification or add additional context in comments.

Comments

0

The syntax you are using is not valid in C. You can get pretty close to this syntax in context of assignment operator by using a compound literal

tfrac multf(tfrac a, tfrac b)
{
  tfrac res;
  res = (tfrac) { a.num * b.num, a.den * b.den };
  return res;
}

Note the (tfrac) part before the {}.

But in your case you can simply use initialization instead of assignment

tfrac multf(tfrac a, tfrac b)
{
  tfrac res = { a.num * b.num, a.den * b.den };
  return res;
}

However, returning to compound literals again, if you prefer, you can use a compound literal to turn the whole thing into an one-liner

tfrac multf(tfrac a, tfrac b)
{
  return (tfrac) { a.num * b.num, a.den * b.den };
}

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.