C log() Function

Definition
In C, log() returns the natural logarithm of x, log base e. log(1) is 0.
You pass one double, and it must be greater than 0. The result is a double. Include <math.h>. For base 10, use log10().
Syntax
Pass a number greater than 0. Start with this call.
| Call | What it does |
|---|
log(1.0) | Returns 0, because e⁰ is 1. |
Include <math.h>. On GCC, link with -lm.
Library declarations
double log(double x);
float logf(float x);
long double logl(long double x);
Parameters
| Parameter | Description |
|---|
| x | Required. A double greater than 0. |
Return Value
| Return Value | Description |
|---|
| Natural log | A double. log(1) is 0. |
| NaN | Returned when x is negative. |
C Examples
Example 1 — Basic Natural Logs
Landmark inputs return clean results; others need more digits.
#include <stdio.h>
#include <math.h>
int main(void) {
printf("log(1) = %.1f\n", log(1.0));
printf("log(exp(1)) = %.1f\n", log(exp(1.0)));
printf("log(2) = %.6f\n", log(2.0));
return 0;
}
log(1) = 0.0
log(exp(1)) = 1.0
log(2) = 0.693147
How It Works
- Include math.h. That declares
log and exp. - log(1) is 0. Because
e^0 = 1. - log(exp(1)) is 1.
exp(1) is e, and log(e) = 1. - log(2) ≈ 0.693. A common constant in growth / half-life formulas.
Example 2 — log vs log10
Same input, different bases — different answers.
#include <stdio.h>
#include <math.h>
int main(void) {
double x = 100.0;
printf("log(100) = %.6f\n", log(x));
printf("log10(100) = %.1f\n", log10(x));
return 0;
}
log(100) = 4.605170
log10(100) = 2.0
How It Works
- Same x. Both functions take 100.
- Natural log.
log(100) asks for the power of e → ≈ 4.605. - Common log.
log10(100) asks for the power of 10 → exactly 2. - Pick by base. Use
log for e; use log10 for decades / digits.
Example 3 — Inverse With exp()
exp undoes log for positive inputs.
#include <stdio.h>
#include <math.h>
int main(void) {
double x = 7.5;
double t = log(x);
double back = exp(t);
printf("x = %.6f\n", x);
printf("log(x) = %.6f\n", t);
printf("exp(t) = %.6f\n", back);
return 0;
}
x = 7.500000
log(x) = 2.014903
exp(t) = 7.500000
How It Works
- Find the exponent.
log(7.5) is about 2.015. - Raise e again.
exp(t) rebuilds the original value. - Round-trip. You get back ~7.5.
- Pair for base e. Use
log + exp, not pow(10, …), for natural-log math.
Frequently Asked Questions
log() returns the natural logarithm of x. log(1) is 0.
x is required. It must be a double greater than 0.
A double. A negative x returns NaN, and log(0) goes toward negative infinity.
Include <math.h>. On GCC, link with -lm.
No. log() is base e. Use log10() for base 10.
Next: log10()
Compute the common logarithm (base 10) of a positive value.
log10() tutorial →About the author
Developer, cloud engineer, and technical writer
I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.
9 people found this page helpful