-1

I'm getting this error when trying to compile my code...

#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <stdio.h>
void powRec(long int firstrNum, long int secondNum)
{
    int n;
    if (secondNum == 1)
        ;
    {
        printf("The result is %ld", firstrNum);
        return;
    }
    n = firstrNum * powRec(firstrNum, secondNum - 1);
    printf("The result is %ld.", n);
}
int main()
{
    powRec(-2, 3);
    return 0;
}

I wonder if the problem is in the printf or am I missing something?

Marek R
  • 32,568
  • 6
  • 55
  • 140
  • `n` has type `int`, but the `%ld` expects a `long int`. – Ian Abbott Nov 27 '20 at 16:41
  • 2
    Does this answer your question? [What is the argument for printf that formats a long?](https://stackoverflow.com/questions/38561/what-is-the-argument-for-printf-that-formats-a-long) – Suthiro Nov 27 '20 at 17:24
  • @ShayHugi when you edit question you should improve it not break it. Your last edit made question unclear and detached from already submitted answer. – Marek R Nov 27 '20 at 17:26
  • There's a bug in your code: you have an extra semicolon after the if statement which will cause the block after it to always execute. – Nacib Neme Nov 28 '20 at 04:27

1 Answers1

1

As the message says, you are invoking undefined behavior by passing data having wrong type to printf().

%ld expects long int, but the passed n is int. You should use %d instead of that to print int. Another choice is changing the type of n to long int to match with the format specifier.

Also note that:

  • You should use indentation to make your code easier to read.
  • The return type of powRec is void, so the line n = firstrNum * powRec(firstrNum, secondNum - 1); (especially the multiplication) is invalid.
  • The semicolon in if (secondNum == 1); { may have your code behave differently from your expectation.
MikeCAT
  • 73,922
  • 11
  • 45
  • 70