+ 1
Why does variables not work for me
I have tried numerous different ways to use variables in c++ but no think works. Help
7 Réponses
+ 3
Variables in any language have some rules to define which is known as variable naming convention
🍎 keywords can not be an variable eg- int int = 5; as int is an keyword which define integer data type is can't be an variable name.
🍎 Variable name must start with an alphabet (A-Z and a-z) or underscore ( _ ) sign, digits(0-9). For e.g. var, X, _name, etc are valid variable names but 1x can't be as start from number symbols such as %, &, @ , etc. For e.g. a_01, findSum are valid variables name but name&, calc% are not allowed in C++.
🍎 first can you please tell for which variable you are facing error or difficulty global variable or local variable
Local variable is an variable which is declare in local scope within the braces
#include<iostream>
using namespace std;
int main() {
int a,b; // local variables
a=5; b=4;
cout<<"a+b = "<<a+b;
return 0; }
+ 2
Global variable is declared outside the main function and have the universal value as the value remain same for the whole exam like pi =3.14 is an global constant and speed of light = 3*10^8 is an universal constant
I would give an example of class and function as you tagged C++
#include<iostream>
using namespace std;
int x; // global variable
void solo() {
cout<<"Inside solo"<<endl;
cout<<"x = "<<x<<endl; }
int main() {
x=25;
cout<<"Inside main"<<endl;
cout<<"x = "<<x<<endl;
solo();
return 0; }
+ 2
Skyler
You should use the variable name without the quotes for printing it's value
#include <iostream>
using namespace std;
int main()
{
int thevariable = 22;
cout << thevariable;
return 0;
}
0
Yes, without seeing your code it's hard to know what your issue might be.
0
ok here you go,
#include <iostream>
using namespace std;
int main()
{
int thevariable = 22;
cout << “thevariable”;
return 0;
}
Ok so thats the code, in console after i run it and build, it only says thevariable and not 22, hopefuly this helps.
0
thanks so much, I was so confused.