Unable to reduce the code (combine cout with exit) - c++

I'm allowed to insert only 10 lines (strict) of codes into my program. I have optimized to program to a concise one. I have posted the code below.
if (std::find(outvar.begin(), outvar.end(), line[x].tokens[0]) == outvar.end() || (std::find(inputs.begin(), inputs.end(), line[x].tokens[4]) == inputs.end())
{
cerr << "Undefined variable " << endl;
exit(1);
}
if (opr[x].type == "MUL" && opr[x1].asap_value == my_cycle + 1)
{
opr[x1].asap_value = my_cycle + 2;
update_slack();
update_matrix(opr[x1].opid, 0);
}
if (latency < (opr[p2].asap_value + opr[p2].latency_op - 1) || opr[p2].asap_value == 0)
{
cerr << "Latency value is too less for this circuit \n"; return -1;
}
This alone takes 10 lines and I have 2 more compulsory lines of codes that has to be added. I'n unable to further reduce it. Basically I'm looking to combine the err(cout) statement along with the exit (return) statement into a single statement.
Any help will be greatly appreciated.
Thank you

You could make this all into one line using commas:
opr[x1].asap_value = my_cycle + 2, update_slack(), update_matrix(opr[x1].opid, 0);
Not sure if this is considered cheating. You haven't specified what the rules are exactly.

You need to understand that there is no obvious relationship between the number of statements and the code efficiency. That is because, for example the statement cout<<x; is not a single instructions for your processor. There can be hundreds or even thousands of instructions that the processor must execute in order to achieve the goal of that statement. Also, there are some statements, like a = b + c; that are translated into 2-3 instructions.
So, by reducing the number of statements, you don't optimize the code. There are other ways of optimization, like using a more efficient algorithm.

Related

Is there a compiler difference between an if-check and inline conditional?

I've recently begun using flags to handle an input loop's validity condition so it can be checked elsewhere inside the loop rather than having to redo the same check multiple times. However, I'm unsure how best to assign the flag. Is there a generally standard practice regarding this, or just personal style? What, differences are there in the compiled code, if any?
For example, instead of the following code:
bool isValidSize;
do {
std::cout << "Enter the font size (8-12): ";
std::cin >> fontSize;
if (fontSize >= MIN_FONT_SIZE && fontSize <= MAX_FONT_SIZE) {
isValidSize = true;
} else {
isValidSize = false;
std::cout << "Invalid size. ";
}
} while (!isValidSize);
the if-statement can be changed to make it more clear what isValidSize is set to at a glance:
isValidSize = (fontSize >= MIN_FONT_SIZE && fontSize <= MAX_FONT_SIZE);
if (!isValidSize) {
std::cout << "Invalid size. ";
}
Would this be compiled as an extra if-check? Is there any portability benefit to having the assignment separate from anything else? From just looking at the code, it seems the benefit of the first way is possibly only one branch but an additional assignment per rep and also has an else?
There are no differences: proof.
Tested on GCC 6.3 with optimisations (-O3).
Go for what you think is the more readable one.

Simple if statement not evaluating to true when it should

if ((!m_pMediaPage->PageLayer() || !m_pMediaPage->LoadState()) &&
!m_pMediaPage->m_bRequestList)
{
GetListInfo();
m_pMediaPage->m_bRequestList = TRUE;
}
GetListInfo() does not get executed when all values are 0.
PageLayer() and LoadState() return ints and m_bRequestList is an int.
Basically rewritten as this:
if ((!0 || !0) && !0) -or- if ((1 || 1) && 1)
I can only assume that the values being evaluated by the if statement aren't really as seen by the debugger.
I am using visual studio 2005 and put breakpoints on line 1 & 4 to examine the values and see if it executes into the if statement. I am not sure how else to debug this.
Like I said, each of the 3 values are 0 as viewed by the debugger when at breakpoint 1.
Functions in .h:
int PageLayer() {return m_iCurrentLayer;} - protected
BOOL LoadState() {return m_bLoadDone;} - protected
BOOL:
typedef int BOOL;
This conditional statement looks as if it would be executed if all values return from the different functions return zero. If the body of the function isn't executed, I would debug the problem as follows:
Log the values of all functions prior to the if-statement:
std::cout << "page-layer=" << !m_pMediaPage->PageLayer() << ' '
<< "load-state=" << !m_pMediaPage->LoadState() << ' '
<< "request-list=" << !m_pMediaPage->m_bRequestList << '\n';
Yes, the debugger should show these values as well but I have great faith in the values being printed to be the values actually evaluated.
If that doesn't give the necessary insight into what goes wrong, I would start breaking down the condition into separate parts and verify success at each level, e.g.:
if (!m_pMediaPage->PageLAyer()) {
std::cout << "page-layer is not set\n";\
}
if (!m_pMediaPAge->LoadState()) {
std::cout << "load-state is not set\n";
...
If this still doesn't give any insight, I'd start suspecting that the functions return funny values and I would verify that the different results are funny values and I would start looking at the output after preprocesing using the -E option.
You tagged the question as VS2005; do you have all relevant service packs installed to ensure you aren't running into some long-fixed compiler issue?
Secondly, the functions you've listed appear to be very simple setters (you might want to make them const, although that is unrelated to your problem).
You're stepping thru with the debugger, it might therefore be valuable to check your assertion that they are all zero:
bool plCond = (m_pMediaPage->PageLayer());
bool lsCond = (m_pMediaPage->LoadState());
bool rlCond = (m_pMediaPage->m_bRequestList);
bool getListInfoCond = ((!cond1 || !cond2) && !cond3);
if (getListInfoCond)
{
GetListInfo();
m_pMediaPage->m_bRequestList = TRUE;
}
If this fixes the problem, you either have a heisenbug or a stack/memory stomp.
If this doesn't fix the problem, it may home in on the cause.
If this DOES fix the problem, you may want to consult the assembly for the code and see if you have somehow tripped a compiler bug.

C++ simple If statement making the rest of the program not execute

I have an assignment where I must read from a file and perform various calculations on it and write the answer to an output file. Everything was going great until I came to this step:
"Reread the file and compute the sum of the integers in the file as long as the sum does not exceed 1000. Use a flag controlled loop structure."
My code snippet is as follows:
dataFile2.close();
dataFile2.clear();
dataFile2.open("J:\\datafile2.txt");
sum = 0;
while(sum < 1000)
{
dataFile2 >> num;
sum = sum + num;
if(sum > 1000)
sum = sum - num;
}
answers << "The sum of the integers not exceeding 1000 is " << sum << endl;
cout << "The sum of the integers not exceeding 1000 is " << sum << endl;
return 0;
My variables have already been declared. when I take out the if statement the sum adds the last number and the sum then exceeds 1000. When the If statement is left in, the answers and cout statements are not executed and there are no compiler warnings or errors.
Any help on this would be greatly appreciated.
-ThePoloHobo
Since no one seems to want to give you a correct answer... (and
to be fair, it's hard to give a correct answer without actually
doing your work for you).
There are two issues in you code. The first is the requirement
that you use a flag. As I said in my comment, the idiomatic
solution would not use a flag, but there's no problem using one.
A flag is a boolean variable which will be tested in the
while, and will be set in a conditional in the loop, when you
find something that makes you want to leave the loop.
The second issue is that you are using num without checking
that the input has succeeded. You must check after the >>
operator. The idiomatic way of checking (and the only thing
that should ever be used by someone not experienced in the
language) is to treat the stream as if it were a boolean:
dataFile2 >> num;
if ( dataFile2 ) {
// Input succeeded...
} else {
// Input failed for some reason, maybe end of file
}
Since all operations on a stream return a reference to the
stream, it is usual to merge the test and the input:
if ( dataFile2 >> num ) {
// succeeded
} else {
// failed
}
(Personally, I find the idea of modifying state in the condition
of an if or a while horrible. But this idiom is so
ubiquitous that you should probably use it, for the simple
reason that that's what everyone expects.)
In pedagogical environments, it's probably acceptable to
consider any failure to be end of file, and just move the test
up into the while (except, of course, that you've been asked
to use a flag). In other contexts, you'll want to take into
account the fact that the failure could be due to a syntax error
in the input—someone inserted "abc" into the file where
you were expecting a number. There are a number of ways of
handling this, all of which are beyond the scope of what you are
trying to do, but be aware that after you've detected failure,
you can interogate the stream to know why. In particular, if
dataFile2.eof() is true, then the failure was (probably) due
to you having read all of the data, and everything is fine. (In
other words, failure to read a data is not necessarily an error.
It can be simply end of file.)
You don't seem to be using a flag variable, which could help in this case. Something like this should fix it:
sum = 0;
bool sumUnder1000 = true; //Or the C++ equivalent, I'm a bit rusty
while(sumUnder1000)
{
if(!dataFile2.good()){
sumUnder1000 = false; //We've reached end of file or an error has occurred
return;
}
dataFile2 >> num;
sum = sum + num;
else if(sum > 1000){
sum = sum - num;
sumUnder1000 = false;
}
}

Check multiple OR operators in IF statement

I have the following C++ code:
if(x==y||m==n){
cout<<"Your message"<<endl;
}
If x is equal to y or m is equal to n, the program prints "Your message". But if both conditions are true,the program tests only one of them and eventually prints one "Your Message".
Is there a way to print each "Your message" independently based on each condition using a single if statement?
The output would be identical to the below using multiple if statements.
if(x==y){
cout<<"Your message"<<endl;
}
if (m==n){
cout<<"Your message"<<endl;
}
Not that I'd ever do it this way, but ...
for(int i = 0; i < (x==y)+(m==n); ++i) {
std::cout << "Your message\n";
}
Let me expand on this. I'd never do it this way because it violates two principles:
1) Code for maintainability. This loop is going to cause the maintainer to stop, think, and try to recover your original intent. A pair of if statements won't.
2) Distinct input should produce distinct output. This principle benefits the user and the programmer. Few things are more frustrating than running a test, getting valid output, and still not knowing which path the program took.
Given these two principles, here is how I would actually code it:
if(x==y) {
std::cout << "Your x-y message\n";
}
if(m==n) {
std::cout << "Your m-n message\n";
}
Aside: Never use endl when you mean \n. They produce semantically identical code, but endl can accidentally make your program go slower.
I don't think that's possible. What you have inside your bracket is a statement which is either true or false, there's no such thing like a true/true or true/false statement. What you could do is a do/while loop with a break statement. But I don't think that's the way to go. Why do you want to avoid two if statements?
single "|" or "&" gaurantees both side evaluation even if the result can be determined by left side operator alone.
You could do something like this, to build up the "message":
string msg = "Your Message\n";
string buildSt = x == y ? m == n ? msg + msg : msg : m == n ? msg : "";
Compiler checks only one condition when both are true because you've connected your conditions with OR.
If even one condition in ORs chain is true there is no need to check others as a result already true and will be false if one of them is false. So if you think that your logic is right then there is no need to do multiple checks. Your code is asking that you will print a message if one of the conditions is true and program doing it. If you want something special for a case when both conditions are true then add it separately. Shortly you should never expect from the compiler to do all checks in the expressions connected by OR.
Regards,
Davit
Tested code:
#include <iostream>
#include <string>
using namespace std;
void main() {
int x=1;
int y=1;
int m=1;
int n=1;
string mess1="Your message 1\n";
string mess2="Your message 2\n";
cout<<((x==y)?mess1:"")+((m==n)?mess2:"");
getchar();
}
If you are trying to see if both statements are true an && is what you will want to use.
Take a look at Boolean Operators to see all of the possible options when comparing boolean (true/false) values.
To answer your question:
if ((x==y) && (m==n))
{
cout<<"Your Message"<<endl<<"Your Message"<<endl;
}
else if((x==y) || (m==n))
{
cout<<"Your Message"<<endl;
}

Best practice for having two if statements from the same bool c++

I have an if statement that [obviously] only runs if the condition is true. After this if statement there is some code that should always run, after that is another if statement that should run under the same condition as the first.
The code in the middle is performing an operation using a particular element of a stack, the ifs on either side perform a push/pop on the stack before and after the operation respectively.
so the logic is something like this:
Do I need to push the stack? yes/no
perform operation on top of stack
Was the stack pushed? (if yes then pop)
items 1 and 3 are the same condition.
This is the code that I first wrote to do this in c++
#include <stdio.h>
#include <stdlib.h>
int somefunction(){
return rand() % 3 + 1; //return a random number from 1 to 3
}
int ret = 0;
//:::::::::::::::::::::::::::::::::::::::
// Option 1 Start
//:::::::::::::::::::::::::::::::::::::::
int main(){
bool run = (ret = somefunction()) == 1; //if the return of the function is 1
run = (run || (ret == 2)); //or the return of the function is 2
if (run){ //execute this if block
//conditional code
if (ret == 1){
//more conditional code
}
}
//unconditional code
if (run){
//even more conditional code
}
}
//:::::::::::::::::::::::::::::::::::::::
// Option 1 End
//:::::::::::::::::::::::::::::::::::::::
After writing this I thought that it might be more efficient to do this:
//:::::::::::::::::::::::::::::::::::::::
// Option 2 Start
//:::::::::::::::::::::::::::::::::::::::
int main(){
bool run;
if (run=(((ret = somefunction()) == 1)||ret == 2)){ //if the return of the function is 1 or 2 then execute this if block
//conditional code
if (ret == 1){
//more conditional code
}
}
//unconditional code
if (run){
//even more conditional code
}
}
//:::::::::::::::::::::::::::::::::::::::
// Option 2 End
//:::::::::::::::::::::::::::::::::::::::
I prefer the first method for readability as it is split into several lines whereas the second has two assignments (=) and two comparisons (==) in the same line.
I want to know if it is better to use the second method (for reasons of efficiency or executable size) or if there is a better method than both.
Before anyone says it will only make an almost immeasurable difference, this is in a huge loop that has to run many thousands of times within 1/50 of a second so I would like to save as much time as possible.
Performance should not be your concern: the modern compilers are usually smart enough to optimize the code in any case. The results will be the same if the code is doing essentially the same thing.
So you should prefer the variant which is more readable (and therefore better maintainable).
I would write something like that:
ret = somefunction();
// I don't know what is the semantics of ret == 1, so let's imagine some
bool operationIsPush = (ret == 1);
bool operationIsOnTop = (ret == 2);
if (operationIsPush || operationIsOnTop)
{
//conditional code
}
if (operationIsPush)
{
//more conditional code
}
//unconditional code
if (operationIsPush || operationIsOnTop)
{
// ...
}
I believe there will be no difference in the performance here. The first reason is that your compiler will probably optimize the code in each case. The second is that you just change the place where operations take place (like "I do A->B->C or A->C->B"), not the amount of operations, so it's always the same amount of computing (1 function call, a couple of == and so on).
However consider that this
(run=(((ret = somefunction()) == 1)||ret == 2))
is pretty hard to read.
Correctness is more important than whether you fold two operations assigning a bool into one (which the compiler will probably do anyway).
For pushing/popping a stack, you should use a scopeguard (original article here). This will ensure that if something throws in the "unconditional bit", which you never really know for sure, then it still runs correctly. Otherwise you get funny a surprise (stack off by one, or overflowing).
if theres a situation that you can split "if-else" to distinct huge loops, it will be faster
rather than
loop { if_1 {some work} if_2 {some other work} }
you can
if_1 { loop {work }} if_2 {loop{same work}}
even more extremely, if you can split the most inner "if" sentences, you can have 10-20(dpending on your situation) distinct huge loops that runs x2 x3 faster (if it is slow bacause of "if")