string declaration before main funciton in C++ [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
i'm new to understanding stri and declaring them. can a string variable = "" ;
i'm confused why you could put a equal sign on a declaration also. is this to declare a function to be empty sort of like a global variable? like int variable = 0; is that sort of like a global string variable? once i change it it'll be stored down in main function and other fucntions?
#include<iostream>
using namespace std;
string variable = "";
int main() {
return 0;
}

The statement you're asking about defines a variable in
namespace scope (in this case, the global namespace). It's more
or less like any definition: except with regards to linkage and
lifetime:
The lifetime is static, which means that the variable will be
initialized before main is entered (in practice, anyway),
and will be destructed after exit is called.
The linkage is external, which means that the name variable
always refers to the same entity, even in different translation
units.
And of course, since the scope is namespace scope, the variable
can be directly referred to from any function in that namespace,
or in any namespace nested in that namespace. And since all
other namespaces are nested in the global namespace, that means
that the variable can be referred to everywhere (unless some
other declaration is hiding it).

You can assign value to a string variable in two ways.
string variable = "";
This means that you declared a variable named variable of type string and you assigned an empty string to this variable.
You can also assign value this way
string variable("");
this means exactly the same as the one above. but here you don't need the equal sign.
Here's a reference which can help you understand strings http://www.cprogramming.com/tutorial/string.html

There are four separate parts to the small example you posted:
1) Include the necessary headers:
#include<iostream>
2) Declare any used namespaces:
using namespace std;
3) Now this is what you are probably asking about:
string variable = "";
This line above is completely independent of the function below. It is declaring a global variable called variable, of type string. It is also assigning a value to it, which just happens to be the empty string i.e. "". You could also have said instead:
string variable = "My name is numLOCK";
So you are just initializing the value of that variable to the specified text assigning aome value to the variable.
4) Next comes the main function. This does the actual work.
int main() {
return 0;
}
Note that you can use the global variable declared above in your main or any other function. You can also declare more variables inside the function. For example:
string someText = "My name is numLOCK";
int main() {
int someNumber = 42;
cout << someText << endl;
cout << someNumber << endl;
return 0;
}
This will print out:
My name is numLOCK
42

Related

What is the difference between constant declaring Global or declaring inside a function where it is used [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
i am declaring a constant (a large structure constant containing string) inside a function and it is used only inside this function.
will it have any execution time impact on my program? '
They will be created every time the function is called (take more time) or only once and the reference will be used through out its life.
If i declare the constant outside the function (global) will it be faster in execution ?
Actually, declaring variables inside of a function is a great practice. If that variable is only to be used inside of that function of course. There won't be any performance differences between the two methods, but making the constant global may require a more creative naming scheme while the one inside the function can be generic. It is only being used inside of that function, after all.
static struct can help you setting it up once and be done with it. This will be coming from data segment and initialise during at the startup. A raw and dirty code below, but will give you some intuition.
#include <stdio.h>
struct A {
int a;
int b;
};
void func(void)
{
static struct A a = {5,3};
printf("FUNC: A.a: %d\n", a.a);
}
int main(int argc, char **argv)
{
static struct A a = {6,4};
printf("MAIN: A.a: %d\n", a.a);
func();
return 0;
}
I would personally move it out of the function body if any other related functions use the variable, as long as you're using namespaces.
Also if its a true constant, I believe you can declare a struct static constexpr, which means that it won't be allocated on the stack every time the function is called (static), even if you declare it inside the function body. It also means that where it can be used at compile time, it will be (constexpr).
#include <iostream>
namespace Test{
struct Test {
char name[11];
int a;
int b;
};
static constexpr Test TEST_CONSTEXPR = {
"test value",
5,
6
};
}
int main()
{
std::cout << Test::TEST_CONSTEXPR.name << std::endl;
std::cin.get();
return 0;
}
In Ada this is compiler dependent. (As performance usually is.)
As "constants" are not compile-time static, a compiler may do the safe thing and evaluate the initialising expression every time the constant is declared.
If it really matters, measure what your compiler does.

How to keep the value of a string?

Hey guys I have a question about variables and If statements.
The reason I am asking is I am assigning tokens in a vector of strings to variables but if my vector only has 3 elements and I try to assign a variable to myVector(5) I get an error.
This is my solution to that problem
std::string element5;
if(myVector.size () >= 4)
(
std::string element5 = myVector.at(4)
}
But that wont change the string outside the if statement? My code works fine if I have exactly 5 elements and no error check but if I'm passing in standard input I wont really know how many elements there are all I will know is that there are a max of 50 elements.
I dont need to ouput any elements just run this code on each one
if(countSubstring(element5,"a") > 0)
{
a = a + 1
}
then I would output a.
how do I make element5 keep its new string?
Problem
Your code here redefines your variable element5:
std::string element5;
if(myVector.size () >= 4)
(
std::string element5 = myVector.at(4)
}
Here you first declare element5 after the first line, and then you re-declare it at the third line in your if statement. That essentially "recreates" the variable element5 for that scope {}. And then of course is poped right after the scope. So you won't see a change in element5 if you try to print it out of the scope.
Solution
Easy, just don't re-declare your variable, and you're all set! Like so:
std::string element5;
if(myVector.size () >= 4)
(
element5 = myVector.at(4)
}
Why is this happening?
Like I said, down in the assembly level the variable gets pushed, and then suddenly when it comes down to another level and the same variable gets re-declared, the global variable gets forgotten about. And as soon as the scope ends:
{
//This is a scope
}
the re-declared variable gets poped off the stack, and we have our original element5 back! This will leave element5 in the same position since you didn't actually change it ;).
Undefined Behaviors(UB)
Don't reference to an out-of-scope object; don't do it!
C++: Reference to "out of scope" object
References
What happens when C++ reference leaves it's scope?
What happens in C++ when I pass an object by reference and it goes out of scope?
Glossary
scope: The "container" a program is currently executing under; for example, let's take this:
int main() {
//1st scope
if (true) {
//2nd scope
{
//third scope
}
}
}
Undefined Behavior(UB):
When in an undefined/unknown state at any time given during the compilation. Compiler does whatever it decides to do, making it a very dangerous Behavior especially if you are writing a big project! Here is a good question/answer to this topic:
https://softwareengineering.stackexchange.com/questions/99692/philosophy-behind-undefined-behavior
You are redefining the string inside the if statement, you shouldn't do that because you want to use the string that has been declared before.
So just replace std::string element5 = myVector.at(4) with element5 = myVector.at(4)

Why the variables defined inside a for loop only exist inside of it?

I was reading C++ Primer by Stanley B. Lippman and at the part of flow control it shows an example of a for-loop like this one:
#include <iostream>
int main(void){
int sum=0;
for (int val=1; val <= 10; val++)
sum +=val;
std::cout << sum << std::endl;
return 0;
}
If I try std::cout << val; outside of the for-loop, the IDE gives me an error. But I want to understand why it happens and how it is different from this code:
#include <iostream>
int main(void){
int sum=0;
int val;
for ( val=1; val <= 10; val++)
sum +=val;
std::cout << sum << std::endl;
std::cout << val;
return 0;
}
Where I can actually print the val value without any problem.
Does it have something to do with local variable considering the for-loop a function that we are using inside of the main?
Every variable has scope, which is (loosely speaking) its lifetime.
A variable declared in the head of a for loop has scope limited to the for loop. When control passes out of the loop, the variable passes out of scope. Exactly the same thing happens to variables declared in a function, when control passes out of the function.
Does it have something to do with local variable considering the for-loop a function that we are using inside of the main?
Nothing to do with functions; there are plenty of other ways to get a scope, including a block:
int main()
{
{
int x = 0;
}
std::cout << x; // error
}
And a for loop is another example.
Its deliberate. Its called scope, Whenever you introduce a block { /*stuff here */ } (and a few other places) the variables inside the block are local to the block and supersede (hide) variables of the same name defined outside the block. It helps to ensure block-local code does not tread on other variables. Can be useful when editing an old codebase and you don't want to accidentally use a wider scoped variable.
The concept behind this is called Scope of the variable. Whenever a variable is created a memory location is assigned to it. So in order to optimize the memory usage scope of the variable is defined.
In the first case, the variable is limited only to the for loop. The variable is created inside at the beginning of the loop, utilized inside the loop and destroyed when the execution comes out of the loop.
In second case, the variable is created outside the loop so it persists till the execution of the program and hence you were able to access it even after the loop.
The variable declared inside the for loop is an example of local variable and that declared outside is an example of global variables.
Not only with the loops, the local variables will also be used in if..else blocks, functions and their usage is limited only within the scope.
Hope this answers your question.
Running this exact code does not turn up any errors for me. I get a value of 55 for sum and 11 for val as expected. Because you defined val outside of your for loop but in main, it should be good everywhere within the main() function to the best of my knowledge. As a general rule, if you declare a variable in between two curly braces without any fancy keywords, it should stay valid within those two curly braces (being "local" to that block of code). I am no c++ guru, so there might be exceptions to that (I am also not sure if "if" statements count as code blocks whose locally defined variables only work within the statement).

Naming constants in C++ [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I am replacing my #defines, for instance #define NUM_SLIDER_POSITIONS 5 for constant variables. Should I keep the old naming like:
const unsigned int NUM_SLIDER_POSITIONS = 5;
Or should I use something more like:
const unsigned int kNumSliderPositions = 5;
.
EDIT: The post has been put on hold, but anyway I'd like to sum up your answers:
Other option would be using underscores as a separators using lower case letters:
const unsigned int num_slider_positions = 5;
Constant identifier.
Regarding the use of a prefix as a way of identifying constants , the most common options are not using it, as it may not add relevant information:
const unsigned int num_slider_positions = 5;
Use a "k" before the name:
const unsigned int k_num_slider_positions = 5;
Or declaring the variable inside a class or namespace, in order to avoid polluting the global scope and providing a more self-explanatory name:
namespace defaults // or "config", or "settings" or something like that
{
const unsigned int num_slider_positions = 5;
}
Client code:
int slider_positions = defaults::num_slider_positions;
I am replacing my #defines for constant variables.
Kudos! :)
Should I keep the old naming like: [all-caps]
If the coding conventions of your project designate constants to be in all-caps, you should (as it spares you an effort). Otherwise, you should not (because it will be confusing later, for maintenance).
Or should I use something more like: [bastardized hungarian convention]
This is up to you. Personally I do not like to add weird letters for my constants, because when reading the code - or writing it - I do not care much that they are constant (and if I try to write into them, the compiler will let me know).
My (personal) choice would be to use a namespace for providing context (instead of a prefix), along these lines:
namespace defaults // or "config", or "settings" or something like that
{
const unsigned int num_slider_positions = 5;
}
Client code:
int slider_positions = defaults::num_slider_positions;
I find this to be a superior alternative, because the context is more self-explanatory (than a "k" in front of it, or a "g" or a whatever else).
It's up to you for any name convention. But for C++ code you may also consider putting constants inside a class that use it, instead of pollute the global scope.
the naming convention of constant name with C++ is use a k followed by mixed case,
for constants defined globally or within a class, As a convenience to the reader, compile-time constants of global or class scope follow a different naming convention from other variables. Use a k followed by words with uppercase first letters
const unsigned int kNumSliderPositions = 5;
see more

Why is this c++ working? (variables with the same name)

Alright, I wanna know why this code is working, I just realized that I have two variables with the same name within the same scope.
I'm using g++ (gcc 4.4).
for(int k = 0 ; k < n ; k++)
{
while(true)
{
i = Tools::randomInt(0, n);
bool exists = false;
for(int k = 0 ; k < p_new_solution_size ; k++)
if( i == p_new_solution[k] )
{
exists = true;
break;
}
if(!exists)
break;
}
p_new_solution[p_new_solution_size] = i;
p_new_solution_size++;
}
The k in the inner for loop shadows (or hides) the k in the outer for loop.
You can declare multiple variables with the same name at different scopes. A very simple example would be the following:
int main()
{
int a; // 'a' refers to the int until it is shadowed or its block ends
{
float a; // 'a' refers to the float until the end of this block
} // 'a' now refers to the int again
}
Alright, I wanna know why this code is working, I just realized that I have two variables with the same name within the same scope.
You seem confused about scopes. They're not "within the same" scope... the for loop's k has it's own nested/inner scope. More importantly, to see why the language allows it, consider:
#define DO_SOMETHING \
do { for (int i = 1; i <= 2; ++i) std::cout << i << '\n'; } while (false)
void f()
{
for (int i = 1; i <= 10; ++i)
DO_SOMETHING();
}
Here, the text substituted by the macro "DO_SOMETHING" gets evaluated in the same scope as i. If you're writing DO_SOMETHING, you may need its expansion to store something in a variable, and settle on the identifier i - obviously you have no way of knowing if it'll already exist in the calling context. You could try to pick something more obscure, but you'd have people using such convoluted variable names that their code maintainability suffered, and regardless sooner or later there would be a clash. So, the language just lets the inner scopes introduce variables with the same name: the innermost match is used until its scope exits.
Even when you're not dealing with macros, it's a pain to have to stop and think about whether some outer scope is already using the same name. If you know you just want a quick operation you can pop it an indepedent (nested) scope without considering that larger context (as long as you don't have code in there that actually wants to use the outer-scope variable: if you do then you can sometimes specify it explicitly (if it's scoped by namespaces and classes, but if it's in a function body you do end up needing to change your own loop variable's name (or create a reference or something to it before introducing your same-named variable)).
From the standard docs, Sec 3.3.1
Every name is introduced in some portion of program text called a declarative region, which is the largest part of the
program in which that name is valid, that is, in which that name may be used as an unqualified name to refer to the
same entity. In general, each particular name is valid only within some possibly discontiguous portion of program text
called its scope. To determine the scope of a declaration, it is sometimes convenient to refer to the potential scope of
a declaration. The scope of a declaration is the same as its potential scope unless the potential scope contains another
declaration of the same name. In that case, the potential scope of the declaration in the inner (contained) declarative
region is excluded from the scope of the declaration in the outer (containing) declarative region.
It might sound confusing in your first read, but it does answer your question.
The potential scope is same as the scope of the declaration unless another (inner) declaration occurs. If occurred, the potential scope of the outer declaration is removed and just the inner declaration's holds.
Hope am clear and it helps..
Because you are allowed to have two variables of the same name within the same scope, but not within the same declaration space. The compiler takes the most-local variable of the appropriate name, similar to how you can 'hide' global variables of name X with a member variable of name X. You should be getting a warning though.
In C/C++ the variable scope is limited by the braces so the following code is valid for the compiler:
int k()
{
int k;
{
int k;
{
int k;
}
}
}