Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
866 views
in Technique[技术] by (71.8m points)

math - What are arithmetic underflow and overflow in C?

What do arithmetic underflow and overflow mean in C programming?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Overflow

From http://en.wikipedia.org/wiki/Arithmetic_overflow:

the condition that occurs when a calculation produces a result that is greater in magnitude than that which a given register or storage location can store or represent.

So, for instance:

uint32_t x = 1UL << 31;
x *= 2;  // Overflow!

Note that as @R mentions in a comment below, the C standard suggests:

A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type.

Of course, this is a fairly idiosyncratic definition of "overflow". Most people would refer to modulo reduction (i.e wrap-around) as "overflow".

Underflow

From http://en.wikipedia.org/wiki/Arithmetic_underflow:

the condition in a computer program that can occur when the true result of a floating point operation is smaller in magnitude (that is, closer to zero) than the smallest value representable as a normal floating point number in the target datatype.

So, for instance:

float x = 1e-30;
x /= 1e20; // Underflow!

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...