Could someone help me with my if-statement so it checks if the variable "a" contains the lowercase letter "e"? Pretend that the variable "a" gets random values everytime the program runs.
public static void check(char a){
if(//Code here//){
System.out.println("if");
}else{
System.out.println("else");
}
}
Related
This is Arduino code, but I have a feeling my error is with C++ in general and not specific to Arduino. I'm new to pointers and strings, so I probably am doing something wrong in that regard.
This is from a much larger program, but I've whittled it down to as little code as I can where I can still reproduce the bug.
It should just iterate through the letters of text[] and save each letter into newText[0][0], as well as print newText[0][0] and the counter variable i.
void setup() {
Serial.begin(9600);
}
void loop() {
const char text[] = "chunk";
static char newText[][10] = {};
static unsigned int i=0;
static int code = 0;
if(code == 0){
newText[0][0] = text[i]; //This
Serial.print(i);
Serial.println(newText[0][0]); //This
i++;
if(i>=strlen(text)){
code=1;
}
}
}
But as I have the code, i jumps to some number like 104 by the second iteration, when it should be equal to 1. (The exact value varies depending on how exactly the code looks.) If I comment out either of the lines that have the comment //This, then the counter works fine. Also, if I switch Serial.print(i); and the line before it, then it counts fine.
static char newText[][10] = {};
This creates a zero sized array (to be more precise a matrix of 0 rows and 10 columns). This would be illegal in C++ but gcc has an extension to allow it. Nevertheless even with gcc's extension, it's UB when you access newText[0][0] which is outside the size of the array. When you have UB anything can happen, the program can appear to work as you expect, it can print gibberish, it can crash, etc., literally anything.
So you need to declare a size that accommodates all your accesses, e.g.:
static char newText[1][10] = {};
if you only want 1 row (but in this case you don't need a matrix, a one dimension array would do fine).
Tip: use the String class for strings instead of raw arrays.
So I have been working on a question and this think stumbled upon me. When I declare a variable outside the main function, the program works correctly, that is it reaches the else case of "Friendship is magic" but if the variable is declared inside it returns Chris instead of Friendship statement.
int mis, chr;
int main() {
int a, n, m;
cin >> a;
for (int i = 0; i < a; i++) {
//code here
}
if(mis > chr)
cout << "Mishka";
else if(chr > mis)
cout << "Chris";
else
cout << "Friendship is magic!^^";
}
The input that I am using makes the value of chr and mis equal so it should be evaluating to the else statement but instead it just stops at else if.
"With great power (provided by C++) there must also come great responsibility"
And
"With uninitialized variables comes the undefined behavior"
Variables that are declared at global scope are being initialized by the compiler. However, the variables defined inside any function (i.e, having automatic storage) may contain garbage values (that could be different in each invocation of the program). I recommend always initializing your variables to some value.
int main()
{
int mis = 0, chr = 0;
// ...
return 0;
}
Let's come to your program now:
When I declare a variable outside the main function, the program works correctly, that is it reaches the else case of "Friendship is magic"
It is happening because the variables (on which your if ladder dependent) are being initialized to 0. Since, both variables have same value (0), the else part of the if statement is being executed.
but if the variable is declared inside it returns Chris instead of Friendship statement.
It's a perfect example of undefined behavior. If they are defined inside your function, they will be holding some garbage value and that might not be equal. Hence, what you are observing is an undefined behavior and you might get different results in different machines or even sometimes in a same machine.
I tried your code and it works the same for me in both cases.
So, I would say it changes with editor to editor and always initialize the variable before using it.
Otherwise, we might face the same problem as you face. As it initializes the variables with garbage values.
The Problem of the Solution is that first line will contain total no. of Input and the next line will take three integer and then we have to calculate the result based on the input.So the Problem with my Solution is that the While Loop is Not Terminating.
I have Checked the code several times and thinks that this is happening because of the conditional statement and because of if-else the --t statement is not getting executed.So,what modifications should i do to make the program terminate after t input.
#include<iostream>
using namespace std;
int main()
{
int t{0};
cin>>t;
while(t)
{
double h{0},c{0},t(0);
cin>>h>>c>>t;
if(h>50 and c<0.7 and t>5600)
cout<<"10\n";
else if(h>50 and c<0.7)
cout<<"9\n";
else if(c<0.7 and t>5600)
cout<<"8\n";
else if(h>50 and t>5600)
cout<<"7\n";
else if(h>50 or c<0.7 or t>5600)
cout<<"6\n";
else
cout<<"5\n";
--t;
}
return 0;
}
I expect the Program to terminate after t input but it is not happening.
Outside the loop you have
int t{0};
And inside the loop you have
double h{0},c{0},t(0);
You have two different and distinctive variables t that shadows each other. And inside the loop when you do --t you decrement the variable inside the loop, not the one you use for the looping condition.
You solve this by using descriptive names for your variables, instead of short one-letter names.
suppose
while(1)
{
{
{
int a=10;
a=5;
}
}
}
now as I cannot refer to "a" after its block's brace. I want to know when control moves up to first brace and then running down visited third brace again will "a" declared again or "a" hold value 5.
A new a variable will be defined in each step of loop.
a will only be declared when you declare it...
You declared it inside an inner scope, so any code referring to a will only be valid inside the same scope. Once you leave that scope, there exists nothing in your program called 'a' any longer. The memory that used to hold the value 5 may now be used by the rest of the program for other purposes.
Logically, the a cant be reference before its declaration, or after the close of the brace pair its declared in. It also gets destructed at the close, but thats a NOP for ints.
Each time around the loop it will be re-initialized to 10.
But, you missed the fun part of the question, about what happens if the declaration doesnt set the value:
while(1)
{
{
int a; // Here Scope Starts
a=5;
}// Here Scope Ends
}
Here, a will be undefined before it is set the first time. But, it will also almost always be in the same place on the stack, so it might possibly retain value from one iteration to the next, if nothing else uses that space. But whether or not it does can be execution dependant, which makes this an exciting source of bugs.
while(1)
{
{
{// Here Scope Starts
int a=10;
a=5;
}// Here Scope Ends
}
}
The variable will logically be reallocated on the stack with each iteration -- in practice, the memory location will simply be reused. But note, in your trivial example, the value of "a" would never "visibly" hold the value of "5" when the loop returns to the declaration on the next iteration because it is explicitly initialized to "10" at the point it is declared. And if C# follows the same practice as Java, it would be implicitly reinitialized to a default value at that point if the compiler does not complain first that an uninitialized variable is being accessed if you do not initialize it yourself.
each iteration of while loop , you will define new variable a and value of "a" change also but if you loop finish by any way you will lose this variable (you can't use it even in same function)!!
a will be declared again.
usually you will define parameter as a in the loop if you do want it to reset each loop so you won't carry values from iteration to iteration.
while(1)
{
{
{
//Define a new `a`
int a=10;
a=5;
}
}
}
But if you wish to use the same parameter and value for all the iterations, you need to define it out side the loop:
int a=0;
while(1)
{
{
{
//`a` will count the number of iterations.
a = a + 1;
}
}
}
Alright, so I'm in the process of learning C++, and I've hit a strange effect while working with one of the tutorials, and I don't quite get while it's happening..
For the tutorial (copied from the example offered), I have written a function within a class template specialization that checks if the char is lowercase, and then makes it uppercase:
char uppercase ()
{
//checks to see if "element"(char) is a lower-case letter between 'a' and 'z'
if ((element >= 'a') && (element <= 'z'))
{
//changes value of "element" to be element + (value of A - Value of a)[-32]
element += 'A' - 'a'; //element = element + -32
return element;
};
};
Now, strangely.. even if the char is already uppercase, this code still gets triggered. So if I call the function with a value of 'j', I obviously get 'J', as intended. However, if I call with a value of 'J', the function still goes through.. so instead of the function not changing anything, it instead returns '*'.
Now, interestingly.. if I remove the brackets from the if statement, it works as intended. So, with
char uppercase ()
{
//checks to see if "element"(char) is a lower-case letter between 'a' and 'z'
if ((element >= 'a') && (element <= 'z'))
//changes value of "element" to be element + (value of A - Value of a)[-32]
element += 'A' - 'a'; //element = element + -32
return element;
};
it works completely as intended. Calling the function with the value 'J' just returns 'J', because the conditions weren't met, and thus no code was executed. Now, I know that braces are optional with if statements, but the tutorial says that braces are required for more than one statement.
It's also worth noting that adding an else to the statement using braces with just a plain return gives the desired effect, but this should be unnecessary, right?
So, basically.. am I missing something about braces, or is this just an issue with the compiler (Visual Studio 2012)?
That's per design, the if takes one statement only, the braces make a block one statement.
If you want scope by indentation use Python.
The problem with your code is that you do not return anything when the if statement does not match, which results in undefined behavior. Your compiler probably gives you a warning about that. Don't ignore compiler warnings.
The second block of code is actually what you want, only change the variable element when your if matches, but always return the variable element.
In the first case, you are not executing a return statement if the condition isn't met. Presumably the function is returning garbage.
In the second case, because there are no braces, only one line is dependent on the condition. The return statement is executed regardless. In other words, your second example is equivalent to:
char uppercase ()
{
//checks to see if "element"(char) is a lower-case letter between 'a' and 'z'
if ((element >= 'a') && (element <= 'z'))
{
//changes value of "element" to be element + (value of A - Value of a)[-32]
element += 'A' - 'a'; //element = element + -32
}
return element;
};
You have an if statement. If the statement evaluates to true, it will execute the operation immediately following it. In order to do more than one operation at once, you must enclose them in curly braces.
You're getting a strange answer with braces because if J is uppercase, your if statement is false, you skip past the braces, and you don't have a specified return value (hence the nonsense return value). You need to say what to return if your if statement isn't true.
Your second piece of code works because only the first line after the if statement is controlled by the if. This is essentially you being lucky here with - if you had two operations you had wanted to do, you'd still be getting garbage. It's generally therefore good practice to explicitly specify what code you want executed by your if statement by putting it in curly braces, even if it's one operation.