Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper use of constants in C

Tags:

c

I just found a bug in my code which can be simplified to:

float c;
int a,b;
a=5;b=6;
c=(a+b)/2;

In my debugging c has the value 5, i.e. integer division was executed.

This leads me to the question: What is a good practice when using numbers that are not stored in a variable, i.e. constant. In my case, the denominator 2.

When I'm implementing mathematical formulas that carry various constant like this, should I always put .0 at the end to make sure its internally used as a double? Does it speed up the operating time of my program? How much extra work has to be done if a constant has to be converted from int to double?

formulas like

z = 180 * 3.1415 * x  + 5*y^2 - (10*x-y)/(y+x);

where x,y,z are doubles.

So my question is,

Is it "clean code" to write all factors with a .0 at the end ? It does decrease readability of the code quite alot, especially if the formulas are very long. But with this convention, I would prevent errors like the one discribed at the beginning.

like image 321
mch Avatar asked Dec 20 '18 16:12

mch


People also ask

How do you use constants in C?

The const keyword Variables can be declared as constants by using the “const” keyword before the datatype of the variable. The constant variables can be initialized once only. The default value of constant variables are zero.

What are the 3 constants used in C?

Primary constants − Integer, float, and character are called as Primary constants. Secondary constants − Array, structures, pointers, Enum, etc., called as secondary constants.

When should I use constants?

Constants are used in programming when a value needs to be available to the program, but it will not change during the execution of the program. What is a variable? A variable is a named container, held by the computer in a memory location.

Where is constant used?

Constants are useful for both programmers and compilers: For programmers they are a form of self-documenting code and allow reasoning about correctness, while for compilers they allow compile-time and run-time checks that verify that constancy assumptions are not violated, and allow or simplify some compiler ...


1 Answers

Constants have a type at compile time, just as variables do. If a numeric constant contains a decimal point and no type suffix then its type is double. If it does not contain a decimal point and no suffix it will be one of the integer types (which one depends on the value of the constant and the range of the relevant types). So there's no speedup or slowdown associated solely with the type of the constant.

When it comes to performing calculations, integer arithmetic tends to be faster than floating point, so as a rule don't use floating point values unless you need to.

like image 106
dbush Avatar answered Oct 06 '22 16:10

dbush