# Constants and an error (C++)

## Recommended Posts

Got back to reading my book (after a couple weeks long hiatus), and I've hit a small snag. I just finished reading about constants and such, and I don't really get it. It's mostly enumerated constants. I think I'm starting to understand regular constants a little, but I don't understand why they'd be useful. Since they can't be changed, what could they be used for? Also, why would enumerated constants be of use? Honestly, I don't even really understand anything about them other then they increment the value up 1 from the previous constant unless specificly defined. One more problem I'm having is a warning I get when I compile a certain code. Not an error. It even "seems" to run properly, but I still get an error. The following code was an excercise in my book. It's custom so that's why it has this warning...
#include <iostream>
int main()
{
unsigned short int my_age;
unsigned short int width;
unsigned short int length;
unsigned long int area;
double star_number;
float rain;
my_age=15;
width=1000;
length=1200;
area=width*length;
star_number=32851891385;
rain=5.4;
std::cout<<"My age is: "<<myage<<"/n";
std::cout<<"The width is: "<<width<<"\n";
std::cout<<"The length is: "<<length<<"\n";
std::cout<<"The area is: "<<area<<"\n";
std::cout<<"Random guess for the number of stars: "<<star_number<<"\n";
std::cout<<"Amount of rainfall last week: "<<rain<<" inches.\n";
return 0;
}

Ok, the warning says...
Quote:
 warning C4305: '=' : being truncated from 'double' to 'float'
This may be no big deal, but I don't want to be creating a massive hole for me to fall into later. Thanks for any help. ~TDOT>

##### Share on other sites
ExcessNeo    619
Quote:
Original post by that dude over there
Ok, the warning says...
Quote:
 warning C4305: '=' : being truncated from 'double' to 'float'

This may be no big deal, but I don't want to be creating a massive hole for me to fall into later. Thanks for any help.

~TDOT>

When assigning a float you must add an f to the end to avoid compiler from converting into a double.

Like so:
float a = 1.2f;

##### Share on other sites
Hi,

Compiler defaults a constant floating point number to double.

a double is a 64-bit float. and a float is only 32 bit.

Generally float is good enough for none-astronomical numbers:
float 4bytes range:3.4E +/- 38 (7 digits)
double 8bytes range 1.7E +/- 308 (15 digits)

if you know that you don't need something like 1.7 * 10^308, then you can ignore the warning.

##### Share on other sites
Ok, so it's as simple as adding an "f" to the end? Cool. Now I just need someone to give me a good explanation as to how/why constants work.

~TDOT>

##### Share on other sites
Jan-Lieuwe    206
The warning you saw came from:

rain = 5.4;

'rain' is a float variable and '5.4' is a double, according to the compiler.

typing:

rain = 5.4f;

or

rain = (float)5.4;

...would remove the warning.

const float RAIN = 5.4f;
rain = RAIN;

...would generate the same code at assembly level.

#define RAIN 5.4f
rain = RAIN;

...will also generate the same code, but you might be frowned upon by fellow coders ;)

##### Share on other sites
empirical2    567
Not sure what you are refering to by constants.

After all

for (int f=0;f<50;f++)

50 is 'constant'

So on to some others.

Costants such as this

#define MAXCARS 150

Now you can use this in code whereever you would have put 150, such as drawing each car (a loop of 150) or checking a function call does not exceed 150.

Now you can change 'max cars' by chagning your one constant.

Another example of use of constants is to decalernumbers are something meaningfull:

#define AT_HELM 0
#define AT_CLOVES 1
#define AT_BOOTS 2
(etc etc)

Now in code where you see

Equipment[i]=AT_GLOVES;

Your assigning gloves to equipment slot I. Much nicer than

Equipment[i]=1;

(What was 1 again?)

or

bool GetPlayerByName(const char * Name)

Name is accepted by the function as 'read only' so you know the function cant start tinkering with it. So you can safly do this:

GetPlayerByName("Mr Nudge");

Some really crappy examples there. If this is not what you meant please specify further.

##### Share on other sites
instinKt    149
Constants are usually just a good technique at giving a human readable name to "magic numbers".

Magic numbers are just raw numbers through the code. These can be very hard to understand to someone else looking at your code, or even you looking at your code later down the track.

float position = 110.1f + -9.8f * time;

Why -9.8? What is 110.1f? Something similar might be better written as
const float gravity = -9.8f;const float initial_position = 110.1f;...float position  = initial_position + gravity * time;

This is not only easier to read, but if you refer to gravity many times in your code, you only have to change one value if you decide for your simulation to be held on the moon.

##### Share on other sites
Ah, ok. I think I get it now. So a constant is basically a more human readable way to express a number that needs to be used throughout the code? And the "f" in the float just identifies it as a float and not a double? (that or rain=(float) 5.4;). Anyway, thanks for all the help guys. Now I can continue in my book without worrying about not understanding something.
Until next time(hope it's not too soon).

~TDOT>

##### Share on other sites
Spoonbender    1258
Quote:
 Original post by that dude over thereSo a constant is basically a more human readable way to express a number that needs to be used throughout the code?

Not just a number. It can be any type of value, but yeah.

As for enums, they're a bit of the same. You often have a set of related constants and sure, you could just make a bunch of constants, but you don't really care *which* numbers they refer to, and you'd like to express that they're related. So you can stick them in an enum:

enum Weather {  Sunny,  Rainy,  Stormy}

Now you've said that you have three constants representing different types of weather. And you don't have to specify which number each of them represent (It's irrelevant if Sunny is internally represented as 1, 2 or 42, the important thing is that it's a different value from the others, and the enum takes care of that)

Or you could have an enum for game state (MainMenu, OptionsMenu, InGame and so on. Again, we just want to be able to tell them apart, we don't care which number each is represented by internally)

##### Share on other sites
ExcessNeo    619
Quote:
 Original post by empirical2Some really crappy examples there. If this is not what you meant please specify further.

Indeed, anything preprocessor other than include guards is what I consider bad coding practise (considering const, enumerators and inline functions lead to the redundancy of #define) because of the ramifications they lead to, #defines will never be seen by the compiler adding mass confusion when given an error message referring to the content of a define rather than a name you can look for.

##### Share on other sites
Yes! Ok, enums make so much more sense now, and I think I get their use too. So if I had a main menu with 3 options (an extension of your example), I could figure out which was chosen by setting an outside variable to a constant set in an enum? Like this...
#include <iostream>int main(){  enum game_state{Single,Multi,Quit};  show=Multi;  if (show==Multi)  {    //do some stuff.  }  if (show==Single)  {    //do soemthing different.  }  if (show==Quit)  {    //end the game.  }}

Not sure how accurate that code is, but something to that general effect? Anyway, thanks again for all the help. and if there's anything else you think you shoudl add or correct me on, please feel free to do so.

~TDOT>

##### Share on other sites
Gluber2007    132
Never ever use #define for constants.
The problem is #define statements are evaluated by the preprocessor not the compiler. They have no scope and thus the writer of a #define statement cannot
control where it will take effect.

The only legitimate uses of #define are for include guards, conditional compilation and for cases where you need compiler generated values in your code.
( __FILE__,__LINE__ etc. )