hh32
hh32

Reputation: 170

Nested function in c?

The aim was to implement a c function, that takes two unsingned int n and m and computes the non-negative result m^n. It also said to ignore possible overlows.

So here is the solution given out by the lecturer:

unsigned int power(unsigned int m, unsigned n) {
int power(int x, int y) {
  int result = 1;
  while(m > 0) {
  result *= n;
  --m;
  }
 return result;
}   

While i understand the algorithm itself, i fail to get why he chose to use a nested function. And also why there is a curly bracket missing.

I would have simply written something like this:

unsigned int power(unsigned int m, unsigned n) {
  int result = 1;
  while(m > 0) {
  result *= n;
  --m;
  }
 return result;
} 

Could somebody please explain, why he chose the nested one and why that's better?

Upvotes: 1

Views: 111

Answers (4)

Arjun Sreedharan
Arjun Sreedharan

Reputation: 11453

C language does not support defining functions inside functions. You can however declare a function inside a function.

gcc has an extension that supports nested functions. See this.

Upvotes: 1

fonfonx
fonfonx

Reputation: 1465

There is probably a mistake in the solution the lecturer gave you. Your code seems correct.

Upvotes: 1

pmg
pmg

Reputation: 108978

Looks like the int version was a copy/paste left over error: there are no references to either x or y.

unsigned int power(unsigned int m, unsigned n) {
int power(int x, int y) {                        /* copy/paste left overs */
  int result = 1;
  while(m > 0) {
  result *= n;
  --m;
  }
 return result;
}

Upvotes: 2

Gopi
Gopi

Reputation: 19874

Nested functions are not supported in standard C and there is a extension in GNU C which supports it but is not a standard.

The code what you have written is good and there is a mistake in the code your lecturer has given you.

To know about nested functions you can look here: https://gcc.gnu.org/onlinedocs/gcc/Nested-Functions.html

Upvotes: 1

Related Questions