Why do some functions name in c write in two lines? [closed] - c++

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 6 years ago.
Improve this question
Why does List MakeEmpty(List L) have to be written in a form like:
List
MakeEmpty(List L)
in Mark Allens Book?

This is just a matter of styling preference; the command here is the same regardless of whether you write:
List
MakeEmpty(List L)
or
List MakeEmpty(List L)
It really doesn't make a difference besides changing the readability of the code. The author of the book you mentioned may find adding some whitespace more readable compared to the conventional method you compared it to.
One way you can differentiate between whitespace and a real compiling difference is the semicolon. Wherever there is a semicolon, the line terminates. In your case, if there was:
List; // Notice semicolon here
MakeEmpty(List L)
Then this would have changed the code (the syntax is wrong here as it changes the original meaning of the code, but I just wanted to make my point with this example).
Adding whitespace makes the code more readable to the programmer; it adds to the style, especially if it is being presented to a larger audience. The amount of whitespace preferred varies from person to person.
I tried to make the simplest example possible here: the main() function. See the 2 ways I wrote it:
Method 1:
int // Return type of function on different line from function name and arguments for function declaration
main(void)
{
cout << "hello" << endl;
return 0;
}
Method 2:
int main(void) // Return type of function on same line as function name and arguments for function declaration
{
cout << "hello" << endl;
return 0;
}
Just like your function declaration, here, the return value data type's position is changed between the 2 samples of code. However, the output is the same: It outputs hello followed by an endline.
Hope this helps. If I've made a mistake anywhere, or you have further questions, ask me in the comments box.

Related

Is there any way to print pyramid star pattern with single line of logic code ? Interviewer asked this Question to my friend [closed]

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 3 years ago.
Improve this question
One of my friend was asked by a interviewer to print pyramid pattern using single line of logic code.
If it is possible then please provide me the solution.
If it is possible...
Yes, it is possible.
One has to cheat by hand adding the declaration out of the header file. And by using "everything on one line" hard to read formatting, rather than maintainable formatting.
Those are silly constraints, though. Not used in real projects.
...then please provide me the solution.
extern "C" int puts(const char *s); int main() { puts(" *\n * *\n * *\n * *\n * *\n***********\n"); }
There is a way to do it in C++ within one line of code.
The only statement needed inside a main() function to print the "pyramid" (or star) pattern is:
for (std::string s = "*"; s.size() < 11; s.append("*")) std::cout << s << std::endl;
The output is:ld be made "One line long"; just group every statement one after another. Also, what if
*
**
***
****
*****
******
*******
********
*********
**********
OBS: If you want to compile it yourself, you should include the proper headers for that. Of course, this will make your source code file more than one line long (it couldn't be different, right), but the main() function would still consist of one single line. Also, note that the stop condition is arbitrary (in this case I set it to 10).
The full code is:
#include <iostream>
#include <string>
int main() {
for (std::string s = "*"; s.size() < 11; s.append("*")) std::cout << s << std::endl;
}
DISCLAIMER
I'm assuming that "one line of code" really means "one single statement", which is the only meaningful question to be asked. "One line of code" is very subjective. C++ doesn't care about spaces/returns, hence, every code could be made "One line long"; just group every statement one after another. Also, what if my definition of "line", which might be 'a 60-characters long sequence', differs from that of the manager, which might be 'a 40-characters long sequence'? Then a code working on my view of "single line" might not work in "manager's single line". Hence, due to the subjectivity of such definition, the only proper thing to ask is to do it in a single statement (or expression), which is what this answer accomplishes.
Now regarding the shape. As far as I am concerned, the "Pyramid pattern", also known as the "Star pattern", isn't exactly a pyramid. Everytime I saw this kind of puzzle, it's been concerned about this "right-angled triangle", and I'm quite sure that this is what was asked in the interview. In fact, drawing a real "pyramid" is quite difficult, since it is a 3D geometry that needs 4 triangles and one square. Hence, regarding definitions, neither my answer nor the other one draws a real pyramid (actually, both print a triangle). Taking into account the programming-world experience, this puzzle is about printing the "star pattern", which is more like the right-angled triangle above.

Performance when using sequence of operations in a single line in cpp [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 5 years ago.
Improve this question
Recently I have started looking into C++ from the basics and got to know (to my surprise) that I can give series of expressions in a single line separated by commas in some cases as below
//it'll execute all the expressions mentioned after condition seperated by comma
for(int i=0;condition;++i,++x,cout<<"in for loop"<<endl,z = z*2);
(x>y)? ++z,z1 = z*2, cout<<"printing statement"<<endl:cout<<"condition failed"<<endl,z = z/2;
Here, I have a confusion after this is working. Is it safe to code in that way or is there any problem coding in such a way?
Please clarify!!!
Correct me if i'm wrong anywhere, I'm just curious to know why most of the programmers don't use this way (I haven't seen such kind of lines anywhere)
The comma operator , evaluates each of its operands in sequence. In standardese, there is a sequence point between the evaluation of the left operand and the right operand.
In a expression which contains a comma operator, the value of the left operand is discarded and the expression takes on the value of the right operand. In both of the examples above, the comma operator is used in a void context, so none of the values are used.
So a statement like this where the value of the comma operator is not used:
exp1, exp2, exp3, exp4;
Is equivalent to the following sequence of statements:
exp1; exp2; exp3; exp4;
The first example is equivalent to the following:
for(int i=0;condition;) {
++i;
++x;
cout<<"in for loop"<<endl;
z = z*2;
}
And the second example:
if (x>y) {
++z;
z1 = z*2;
cout<<"printing statement"<<endl;
} else {
cout<<"condition failed"<<endl;
z = z/2;
}
Note that this is considerably more readable that the one-line versions. It's also easier to debug. Since debuggers typically step through code a line at a time, it breaks up the flow and is more granular.
Not indenting and spacing your code is not less costly regarding performance. It is unreadable, confusing and a pain to understand for you and for anyone who'd have to work with it.
Lot of people will prefer a well-syntaxed, beautifully and efficiently-indented code than a top-performance one. You can modify, debug and refract a code which might not work but has the advantage to be understandable.
On the other hand, very few codes remain unchanged and stay unread. There will always be a time when someone, may be you, will have to read it again and if it looks like the one if your OP, it will be very time costly to do.
It is allowed. In my opinion and i say without a reference that in general other programmers do not find your 'for' loop very readable. Sometimes in a for loop you want to do other things then just for (int i = 0; i < 10; ++i){"do something"}For example increment 'i' in every loop with two. Reading code should be like reading a text. If you are reading a book you do not want it to be unnecessary difficult.
Your other question was about the safety of the statement. The biggest problem with the code is that you might get confused about what you are doing exactly. Bugs are caused by human errors (computers are deterministic and are executing machine code which ultimately has been written by a human) and the question about safety mainly depends on how you define it.
To give you some tips. When i just started programming C++ i looked a lot on CPP reference. I will give you a link where you can read about the syntax and what is allowed/possible. On this website there are quite a lot of examples on all kinds of statements. They will in general not put 5 or 6 operations within in a single line. If there are more variables that you want to change then you might want to do that in the scope of the for loop so it will be more readable instead of inside the for loop.
http://en.cppreference.com/w/cpp/language/for

assign and compare coding style [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 7 years ago.
Improve this question
I've been criticized (without real arguments) for using assign and compare like this in my c code:
if (!(buffer = malloc(1024))) {
// handle failure
}
instead of:
buffer = malloc(1024);
if (!buffer) {
// handle failure
}
To be clear: This is not about malloc() but only about doing assignments within condition statements.
Personally I prefer the prior version from an aesthetic point of view.
Also if I do a git grep -E "if \(\!\(.* = .*\)\)\) \{" in order to identify similar constructs in the current Linux kernel source I find a few hundred identical assignments inside if conditions, e.g. in net/ipv4/ipconfig.c:
if (!(d = kmalloc(sizeof(struct ic_device), GFP_KERNEL))) {
rtnl_unlock();
return -ENOMEM;
}
Also used frequently in boost:
// boost/lexical_cast/detail/converter_lexical.hpp
if (!(i_interpreter.operator <<(arg)))
return false;
// boost/iostreams/filter/newline.hpp:
if ((flags_ & f_has_LF) != 0) {
if ((success = boost::iostreams::put(dest, LF)))
flags_ &= ~f_has_LF;
} else if (boost::iostreams::put(dest, CR)) {
if (!(success = boost::iostreams::put(dest, LF)))
flags_ |= f_has_LF;
}
So - apart from your personal opinion - are there good technical arguments for or against doing an assignment and comparison in one statement?
As far as I can tell, the argument against your version tends to be along the lines of "people don't expect to see operations in a conditional". Indeed, when looking over C-like code it takes me a little extra mental effort to spot the socket, bind and listen calls when they're stuffed in an if, because I'm expecting an if's condition to check things, not do things.
But that's about it.
I honestly don't see a marked difference in readability. I prefer yours, actually.

C++ Multi-Dimensional Array saving/loading to file error [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 7 years ago.
Improve this question
I've been working on this C++ project for roughly 2 weeks now and I'm stumped on a couple things regarding 2D Arrays. To start off here is the code I wrote as of now:
http://pastebin.com/vCsz947Q
I decided to provide this as a pastebin link due to the fact that it's rather large (it uses 8 functions) and I thought it would save space in this post. I'm new to this site so I apologize if there's a better way that I'm not aware of.
The Problem:
When I go to save my "char seating" array to a .dat file using the "save seats" function that I created, I get a file that gives me the following garbage character " Ì " instead of the intended ' # ' (for open seats) or ' * ' (if a seat is bought).
My functions will save the intended amount of rows (15) and columns (30) despite this though. Also an asterisk will be placed when I go to "purchase a seat" in this program in the file. Additionally my program loads the files as intended, except for the fact that... Well... There's garbage data stored in the seat array.
I feel like this relates to another problem I'm having where if I go to the "purchase seats" function and I say to purchase a seat, it should replace a # with a *, but it doesn't, yet in the saved file it will show an asterisk in the intended spot... Which is very strange.
I have absolutely no idea why this occurs, and what's frustrating is this one thing that's preventing me from finishing this program. I want to believe that my original array in int main that's being called by other functions isn't being updated properly, but I don't know, which is why I came here to seek assistance.
Thank you for your assistance whoever can help.
Well for a start you have some undefined behaviour here inside your displaySeatingChart (char displaySeats[ ][30], float displayPrices[ ]) function with the following:
const int rowDisplay = 15;
const int colDisplay = 30;
as later within one of your loops you have
cout << displaySeats[rowDisplay][colDisplay];
which is clearly reading beyond the array bounds since in main() you define
const int rowMain = 15;
const int colMain = 30;
char seating[rowMain][colMain];
float seatPrices[15];
and pass both seating and seatPrices to the displaySeats function. There may well be other problems with your code but this at least is a clear example of undefined behaviour. Consider stepping through the code with a debugger to get a clearer idea of the source of the issue.
On another note given that you are working with C++ consider working with std::vector instead of arrays. This will give you more scope to ascertain the dimensions of the items that arrays that you are working with from within your utility functions and result in less potential for errors in array access.

How to write a function prototype? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
my question is write function prototypes for
A function, isAbleToVote, which accepts the age of a potential voter (as a double). The
function should return true if the value of the double is greater than 18 and return false
otherwise.
I wrote bool isAbleToVote(double)
A function, named printPrice, to print a product name and its price to the screen. Both
outputs (i.e., the product name and its price) are passed in as arguments.
I wrote Void printPrice(string product_name, double price)
A function, sizeOf, which accepts a string as its argument. The function should return the length of the string.
I wrote string.length sizeOf(string)
4.A function, named getInt, to print the following message to the screen “Please enter an integer”, and to return the value of the user input.
I wrote cout getInt("please enter an integer")
Am I write? if not what am i doing wrong?
You did well on 1 and 2, those are function prototypes. Though remember, C and C++ function prototypes are followed by a semicolon (to be pedantic)
3 is close, but string.length isn't a return type. Find the return type that best represents the length of a string (hint check the std::string::length() function or strlen() function).
4 is not a prototype. It is a statement. prototypes are simple the signature, without any code body. Read the requirement again and think of the minimal input and output data for the function. Hint there is nothing wrong with a void function that takes no arguments, if you don't need any input or output values.