C/C++ :: Difference Between Literal And Symbolic Constants?
Jun 29, 2014
"A constant, like a variable, is a memory location where a value can be stored. Unlike variables, constants never change in value. You must initialize a constant when it is created. C++ has two types of constants: literal and symbolic.
A literal constant is a value typed directly into your program wherever it is needed. For example, consider the following statement:
long width = 5
This statement assigns the integer variable width the value 5. The 5 in the statement is a literal constant. You can't assign a value to 5, and its value can't be changed.
The values true and false, which are stored in bool variables, also are literal constants.
A symbolic constant is a constant represented by a name, just like a variable. The const keyword precedes the type, name, and initialization. Here's a statement that sets the point reward for killing a zombie:
const int KILL_BONUS = 5000;
Whenever a zombie is dispatched, the player's score is increased by the reward:
playerScore = playerScore + KILL_BONUS;
If you decide later to increase the reward to 10,000 points, you can change the constant KILL_BONUS and it will be reflected throughout the program. If you were to use the literal constant 5000 instead, it would be more difficult to find all the places it is used and change the value. This reduces the potential for error."
what's the difference? Here is a program to demonstrate what I'm having trouble conceptualizing.
#include <iostream>
using namespace std;
int main() {
int width = 10, length = 10;
int area = width * length;
cout << "Width: " << width << endl;
cout << "Length: " << length << endl;
cout << "Area: " << area << endl;
return 0;
}
Now, why would it be harder to go in and changed a regularly defined integer than one defined with the 'const' keyword proceeding it? For example, the width and length variables. My confusion comes from the point that they seem to both simply be variables with a value assigned to them. I feel as if the process of having to change a literal constant's value is synonymous to the process of having to change a symbolic constant's.
View 3 Replies
ADVERTISEMENT
Feb 17, 2014
My assignment is to create a simple stock broker program that ask the user how much they are willing to invest and ask what company they would like to invest in. Finally it outputs how many shares the user will have based on their investment amount. My code is below. My professor said to declare symbolic constants and factor out the if else statements. Ive been struggling trying to understand constant variables. How do I use const variables to factor out the if else statements?
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
//Declare Variables
const double BAC = 16.7;
const double Citigroup = 49.52;
[code]....
View 4 Replies
View Related
Mar 2, 2013
This error keeps coming.
******************************************************************
CSCI 240 Program 5 Part 2 Spring 2013
Programmer:
Section: 1
Date Due: 3/1/13
Purpose: This program uses functions to calculate the surface area of various shapes. It is an exercise in learning to write functions.
******************************************************************/
#include <iostream>
#include <iomanip>
using namespace std;
#define PI 3.14
//Symbolic constant for the value of PI
int Menu();
int getValue( string prompt, int lowerBound, int upperBound );
[Code] .....
View 10 Replies
View Related
Nov 21, 2013
What's the problem with the following:
Code:
#define K 3;
int max(int a, int b) {
return a>b? a : b;
} int main() {
cout<<max(K, K+3);
return 0;
}
Why is it not allowed, and how is it different from:
Code:
int max(int a, int b) {
return a>b? a : b;
} int main() {
cout<<max(3, 3+3);
return 0;
}
View 3 Replies
View Related
Nov 18, 2013
I am working on a code that is suppose to get vowels and consnants from a string. So far i got up to trying to get the vowels from a string. this is what i have so far:
#include <iostream>
#include <string> // includes go into header
using namespace std;
int getword(string word);
int getvowels(string word);
[Code] .....
View 2 Replies
View Related
Apr 3, 2015
I would like to know how can i set a constant attribute in the constructor. This attribute is an int value that cannot be changed.
For instance:
class Test {
public:
const int x;
public:
Test(const int val);
[code].....
With this code i get compile error!
View 5 Replies
View Related
Nov 19, 2014
I have a templated class that can either use float or double as type.
My question is now: What do I do with constant numbers in the code?
Let's assume I have a multiplication by 0.5:
In the case of float type, I want: 0.5f
In the case of double type, I want: 0.5
One answer would be to check for every constant the type and doing an if/else, but this is very annoying with lots of constants.
The code using these constants infer their type automatically by the assignment, that's why I have to take care of the constants.
View 1 Replies
View Related
Mar 6, 2015
was just curios to know if there is a way to make the preprocessor compare against constants defined like this: Code: uint uint_max = -1;
View 1 Replies
View Related
Oct 13, 2014
I need to write a program in which you do the following:
Define three named constants using the appropriate data types:
DEC_NUM = 65;
HEX_NUM = 0x7a;
LETTER = 'f';
Then display each of these constants in decimal, in hexadecimal, and as a character using cout. Your program will have a total of nine cout statements.
View 1 Replies
View Related
Sep 28, 2013
why strcmp() doesn't return true when comparing a string constant with a string that was acquired via a linked list. By the way, the data in the linked list was taken from a text file. Does that imply that there's a new line () character in the string from the linked list?
Code:
struct Node{
char ACNO[15];
struct Node *next;
[Code]....
View 1 Replies
View Related
May 23, 2014
I'm playing around and wrote a tiny program.
Code:
char bracketin[] = "thisgetsbracketed.txt";
char bracketout[] = "bracketed.txt";
char testwalk[10] = "12345678";
[Code]....
I'm incrementing the pointer to buffer 150 bytes beyond its reserved 50. I see testwalk, followed by bracketout, followed by bracketin printed by the overflow on buffer.
The memory locations are ordered descending from their call order. Why is this the case?
One would think that they would be written in ascending order as I call them. I can only assume that they're compiled bottom up - where could I read about this process?
View 3 Replies
View Related
Apr 5, 2012
I have a huge xml file from which the key and value attributes are selected among other things.
Code:
foreach (
XmlNode node in
configProductCode.SelectNodes("/configuration/appSettings/add"))
{
ConfigProductCode cpc = new ConfigProductCode();
XmlAttribute keyAttr = node.Attributes["key"];
XmlAttribute valAttr = node.Attributes["value"];
// etc
}
How does C# handle the instantiation of literal strings? does it make a new object with allocating heap memory on every iteration or just once?
View 2 Replies
View Related
May 28, 2013
I have a binary identifier which I tried to make a constexpr since all of its calculations would never occur during runtime (this is true for literal identifiers, right?). Since constant expressions can only have one instruction, I tried to cheat a little and returned an immediate call to a lambda function. This failed miserably however. I tried making a constexpr function pointer and called that from _binary down below, but the compiler still felt that it wasn't a constexpr. Why is this? And is there a way to make a function like _b below constexpr?
#include <iostream>
#include <cstddef>
using std::cout;
using std::endl;
long unsigned //Original
operator"" _b(const char* const literal, size_t lsize){
[Code] .....
View 4 Replies
View Related
Jul 14, 2014
In C++ there are a number of primitives that are not defined in terms of other types. By this I'm thinking
int a = 1;
char b = 'M';
float c = 3.45f;
short d = 0xC3A3;
Is it possible to define your own literal? What I would like to do is have a hex literal for a data type where n = sizeof(data_type). If this type were a big integer, then I would want something like:
BigInt e = 0x13CA9B0C98D983E912DA0B0A9F87E0;
My goal is to assign a value from one contingous chunk of bytes and to not do it with a string.
View 1 Replies
View Related
Sep 13, 2013
In another forum, this example code fragment was stated as being an example of undefined behavior. My understanding is that a literal string exists from program start to program termination, so I don't see the issue, even though the literal string is probably in a different part of memory.
Code: /* ... */
const char *pstr = "example";
/* or even */
char *pstr = "example";
/* as long as no attempt is made to modify the data pointed to by pstr, */
/* unless pstr is later changed to point to a stack or heap based string */
View 11 Replies
View Related
Jan 8, 2014
This compiles o.k.:
Code:
int main(void){
char *a;
a = (char*) malloc (100*sizeof(char));
[Code]....
I get an error saying "pointer being freed was not allocated". This happens for free(a), free(*a), free(&a), free(&*a).
So if I no longer need "1234567"... how do I get rid of this memory element?
View 7 Replies
View Related
Sep 8, 2013
i have 1 nice write() function:
void write() {
cout <<"";
}
template <typename A, typename ...B>
void write(A argHead, B... argTail) {
cout << argHead;
write(argTail...);
}
these function works. but if i concat literal strings with '+', i must use '(string)'. so i'm trying overload the operator + for concat literal strings, but without sucess:(
string operator + ( char *value1) {
string value2;
value2=(string) value2+value1;
return value2;
}
(these functions are inside of my Console class)
View 2 Replies
View Related
Apr 19, 2014
In the following char array, notice the use of a backspace character in a string literal: ''.
char text1[50] = "aHello,
World! Mistakee was "Extra 'e'"!
";
What exactly does a backspace character do here? When the compiler evaluates this line, does it actually delete the previous character, like when you press the backspace button on the keyboard?
View 1 Replies
View Related
Oct 6, 2014
how string literal that works with the cin object?
char * str = "This is a string constant";
Is the str stored the address of the first character of the string literal?
But some books just state that the pointer-to-char (char pointer) stores the address of the string literal". So just wonder how it is.
When it is used with cout, cout just treats it like a string and instead of printing the address, it just prints out all characters one by one until it reaches the terminated null character.
If this is the case, then I am just wondering how cin works with it? with a statement like this cin >> str; ?
Does the computer allocate enough memory for it? and then cin stores the first character into the first address and then advances to the next address and stores the next character?
View 1 Replies
View Related
Feb 23, 2015
I have a struct like this:
Code:
struct String{
char* data;
std::size_t size;
};
I would like to be able to create const variables of this type for string literals.
Code:
const String message;
Is there an elegant way to create a const String like this when data is a string literal?
I tried this:
Code:
const char *string_data = "Hello";
size_t string_size = strlen(string_data) + 1;
const String string = {string_data, string_size};
The problem with that is that string.data isn't considered const during the initialization of the String struct so the compiler throws an error. It doesn't feel very elegant to do it like this either way.
Is there an elegant solution to this problem? I would like to avoid making a copy of the string literal.
View 7 Replies
View Related
Mar 20, 2014
What shall I learn in order to send values from 0.00 to 5.00? I'm working with they Hitachi 16x2 LCD display.I've been sending/displaying literal values on it all day.
Code:
SendCharater(unsigned char val)
where the variable val corresponds to the LCD character table.I can also send Hello World to the display, like so:
Code:
void putsXLCD(unsigned char *buffer){
while(*buffer) // Write data to LCD up to null
{
while( BusyXLCD() ); // Wait while LCD is busy
SendCharacter(*buffer); // Write character to LCD
buffer++; // Increment buffer
}
return;
}
I could type in putsXLCD("5.00") in order to display it on the LCD, but how do I implement this automatically for values, e.g. 0.00 to 5.00?It appears I can only pass literal values through the function SendCharacter, meaning that in order to display "0" I have to pass the value 0x30 (the hex value of "0" on the LCD Table).
My current thought process:Much like passing "Hello World" in the function putsXLCD(), I need to assign a pointer that points at each value in the "array" that I need to send. E.g., I need to send 3.24, so I need to point to "3", fetch the corresponding hex value in the LCD table, in this case 0x34, and the pass this 0x34 into the SendCharacter function, and so on. So, if this is the case, how can I fetch the corresponding hex value?
View 7 Replies
View Related
Jul 10, 2014
I'm making a .json loader for a project that I'm working on, and to simplify things, I decided to make all the root attributes named in a separate file. Here's my problem: my loading function, Add(const char* id), works just fine when I pass it a string literal.
However, when I use a function that iterates through a vector list, even with the exact same definitions as the literal, it returns the error: std::out_of_range at memory location 0x0026fb30
I've stepped through it with the VS2010 debugger about a hundred times, checked against memory locations, and just have done everything I can think of, all to no avail..
The code, with data-checking omitted:
The std::map I'm adding to:
static std::map<const char*, Item*> *s_mItems;
Initialized as std::map<const char*, Item*> *Item::s_mItems;
Add() Function (Works by itself with a literal):
static bool Add(const char* id) {
...
std::string name = node.Get("name").ToString();
std::string desc = node.Get("description").ToString();
int rarity = StrToRarity(node.Get("rarity").ToString());
[Code] ....
AddList() function, where the program always breaks:
static void AddList(std::vector<std::string> list) {
for(std::vector<std::string>::iterator it = list.begin(); it != list.end(); it++) {
Add(it->c_str());
}
}
View 3 Replies
View Related
Jan 24, 2014
Background: I'm using SDL and CodeBlocks and trying to make a Graphics class that would simplify some SDL operations such as drawing and loading images.
Issue: The loadImage function in the graphics class fails to load the image correctly and so the program prints out a blank window during run-time. I've tried multiple ways of passing a string literal into the function the surface temp fails to load and so background in Game fails to load. After testing it several times, I'm pretty sure that the issue lies with SDL_LoadBMP not registering the passed variable for whatever reason. I know the image is in the right place as writing SDL_LoadBMP("./Graphics/image.bmp"); brings it up just fine.
Current Code:
Main simply creates a Game object and execute(), so I didn't feel the need to put it on here.
Game.h
#ifndef GAME_H
#define GAME_H
#include "SDL/SDL.h"
#include "SDL/SDL_ttf.h"
#include "Graphics.h"
#include <string>
#include <cstring>
using namespace std;
//GLOBAL CONSTANTS
//game window settings
[Code] ....
Output: A blank window. (It should show the background image but doesn't.)
Note: I originally wrote it as gfx.loadImage(background, "./Graphics/image.bmp") but that gives me a conversion warning and still fails to show the image when the program runs. I've tried looking up examples similar to what I was doing but no one else seems to have this problem.
View 3 Replies
View Related
Feb 5, 2013
I am wondering if I have the following parameter to pass in to a function
Code : void Load(std::wstring filename);
This statement is wrong.
Code : Load("DataMesh.x");
I don't want to pre-declare a variable. How do I directly pass a wstring (literal) to this function.
View 2 Replies
View Related
Oct 19, 2014
Very new to programming, and I know that there must be another way on inputting a string into each array cells not by just inputting it one by one, but as a whole. My code at the meantime is: [URL]
View 1 Replies
View Related
Jan 26, 2013
#include <functional>
using namespace std;
template<typename...Args>
void on(function<void(Args...)> f) {
function<void(Args...)> fn; // this line causes error C2059: syntax error : '<fake-expression>'
}
int main() {
function<void()> f;
on(f);
}
What's the difference between 'f' and 'fn'?
View 3 Replies
View Related