deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I would go so far as to say never use rand()

Unless you wrote it, of course. ;) I'm at the point with my C standard library that I use it instead of the built-in standard library for most personal work. rand is implemented as the Mersenne Twister, so I know it's solid at least in terms of the underlying algorithm.

In C++, I agree that there's really no excuse to ignore the <random> library if your compiler conforms sufficiently to C++11.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Why is this so?

rand is always seeded with 1 by default, so unless you change the seed with srand, the sequence will be consistent.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

So yes, you can determine what the original source code looks like if there is no obfuscation/cryption.

For .NET to a certain extent. It won't match the original source since higher level constructs are represented internally with lower level constructs, but you can get close enough to have a fairly good view of the implementation.

For C++, it's compiled into machine code and the original is lost completely. So any decompilation will be nothing more than an educated guess at the original code as it builds new source from the machine code.

For .NET, I quite enjoy decompiling assemblies to see how they work. For C++, I don't bother with decompilers and instead use disassemblers and work through the assembly listing. I have yet to see a C++ decompiler that's worth a damn.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

total += float read_input( a,b , c ,d,e );

The syntax is wrong for this line. First, the float keyword is unnecessary (perhaps you meant it to be a cast?). Second, read_input does not accept any parameters, so the arguments are also not needed. Try this instead:

total += (int)read_input();

Finally, read_input is defined to return a value, but doesn't actually return a value.

On a side note, consistent formatting would make your code easier to read.

Abdul_32 commented: thank you soo much you've solved my mess ^_^ +0
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

then the type of the expression is

The longest, floatiest type.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Obviously, the computer could not operate.

Given the usual architecture, yes. But it's not inherently required for RAM to be present, otherwise paging into virtual memory wouldn't be a valuable solution to lack of sufficient RAM. All memory work can be done from longer term storage, though it would be orders of magnitude slower. At the very least all you need would be CPU registers to perform calculations, and even that could be eliminated with a different (though vastly sub-optimal) processor design.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

So much for my theory that avatar and usernames reflect people's personality!

I have no idea what you're talking about. Mine is a perfect match for my personality. :D

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

In this case the first is more readable and easier to code right?

If all you need is read-only context, sure. Two cases where it's not easier is when you want to index of the enumerated item and when you want to replace the enumerated item. A foreach loop isn't inherently conducive for either, and that's where a for loop is simpler when iterating over a collection.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Screenies of old Daniweb isn't half as interesting as the code for old Daniweb. Eew. ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

At the very bottom of every page are lists of links, which include the article workshop that's filtered based on your user permissions.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

You can't (easily) delete the file while it's locked for reading, so I'd alter the logic so that you break out of the reading loop, destroy the reader object, then delete the file safely.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Linked lists are elegant, but inefficient to keep sorted.

Not if you use a hybrid tree/list, hash/list or a skiplist. :D But those implementations aren't as blindingly simple as a regular linked list, so you don't see them often.

Data structures are an exercise in trade-offs. You can have simple or efficient, but rarely both unless the application is very niche.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Just got a jab in my gum to numb it, and the dentist yanked it out.

I had to go down and have all four cut out since they were all impacted. Recovery wasn't that bad though. I've had worse surgeries.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

PLEASE HELP AS SOON AS POSSIBLE.

Please read our rules as soon as possible. Thanks.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

when one left side and one right side child complete then system credit 700 to parent id

I don't understand your question. Do you mean when a node has two children, 700 is added to a value in the node?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

This is C, there's no magic. So you'll need to acquire the size of each string somehow or make an assumption of the most reasonable largest string. I used the latter approach in the second example by using 1024 as the size of the temporary buffer. It's simpler, but there's a greater risk of failure if you choose the upper limit poorly.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

You have an array of pointers to random memory, not an array of pointers to infinite memory usable by your program. This code practically begs for segmentation faults due to trashing memory. You need to either specify a size for your strings:

char bookName[N][50] = {0};

for (size_t i = 0; i < N; i++)
{
    if (scanf("%49s", bookName[i]) != 1)
    {
        break;
    }
}

Or allocate memory dynamically:

char *bookName[N] = {0};
char buf[1024];

for (size_t i = 0; i < N; i++)
{
    if (scanf("%1023s", buf) != 1)
    {
        break;
    }

    bookName[i] = malloc(strlen(buf) + 1);

    if (bookName[i] == NULL)
    {
        break;
    }

    strcpy(bookName[i], buf);
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Not sure about the live Q&A part, it could be hard to gather a sufficient audience for that

Well, more like a video demonstration allowing topical questions that I can try to answer as I go, or at the end.

I have held on, for about a year now, to the hope of eventually seeing you demonstrate the proper way to do object-oriented programming in C.

I wasn't even aware of this interest. I'll see what I can come up with. :)

Creating functions that use inline assembly is another semi-dark art of C that I'd love to see explained properly.

That's a good one too, though I haven't found a whole lot of use for inline assembly lately in my own work.

I would appreciate your take on subjects of "C for the C++ programmer"... i.e., like tips and tricks or advantages and disadvantages of C techniques that relate to common C++ patterns.

That's a really good one, even though most of the topics would boil down to "how to write code when C++ isn't holding your hand". ;)

I wasn't aware the C standard library had a hood...

I have about 10,000 lines of simplified C standard library code that suggests otherwise. Certainly quite a bit shorter than even a simplified C++ standard library, but there's still a surprising amount of work hidden by the functions we use every day. And the library isn't finished either. A few …

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

You must declare int main() and return a value at the end.

Yes to the first part, no to the second. If there's not a return statement in main, 0 will be returned automagically. It's a stylistic choice whether to include a (redundant) return statement for consistency with non-magic functions.

Of course, if the compiler is Turbo C++ then that's all irrelevant since the compiler doesn't sufficiently conform to any C++ standard.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

thanks guys u lost the chalnge

Believe it or not, we can tell the difference between a legitimate challenge, and a lazy student trying to trick others into doing their homework. Your 'challenge' is clearly the latter.

c u in a next question

I hope not, we already have enough cheaters trying to dump their homework on us.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Actually this should probably be moved to snippets

Done. :)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

So whenever possible and performance is not an issue you would advise this sort of programming practice?

I wouldn't say whenever possible. Clarity trumps, so if duplicating code makes it easier to understand, that would be my recommendation. And if eliminating duplication is excessively confusing for one reason or another, I'd refrain. But in my experience those situations are somewhat rare if the code is otherwise well designed.

ddanbe commented: OK +15
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Hmm, I guess I should have added the 'sarcastic smiley face' when I did that.

Not to diminish the qualities of the forum though, it seems very well designed. Though I haven't used it enough to say that it's solidly functional, I'm confortable making that assumption in this case. Props to the real developers. ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I'm a little biased as this kind of thing is something I use liberally to avoid duplication, but it's also a good practice in general.

One thing to note though is performance. Refactoring into methods and lambdas does tend to introduce overhead, and you should take that into consideration for the possibility of larger matrices.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I have a feeling that WojTroll will go quiet now...

Or create another account in the hope that we won't be able to tell (which we most certainly will).

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Ooh, forum drama.

grabs popcorn

cereal commented: lol +0
RikTelner commented: *passes coke* +0
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I know the reason

And you're correct.

Can you tell how to implement it without using global variable (I always try to avoid sharing variables), sting library, and dynamic memory allocation..

You only have one option with those restrictions, and the only option is to have the caller provide a buffer. Something like this, I suppose:

#include <stdio.h>

char *substr(const char *src, size_t index, size_t size, char *buffer, size_t n)
{
    int length = 0;

    while (src[length] != '\0')
    {
        length++;
    }

    if (index > length)
    {
        return NULL;
    }
    else
    {
        int i, k = 0;

        for (i = index; src[i] != '\0' && k < size && k < n - 1; i++)
        {
            buffer[k++] = src[i];
        }

        buffer[k] = '\0';
    }

    return buffer;
}

int main(void)
{
    char buf[BUFSIZ];

    printf("'%s'\n", substr("Hello World", 0, 5, buf, sizeof buf));
    printf("'%s'\n", substr("Hello World", 6, 5, buf, sizeof buf));

    return 0;
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

You need to initialize the pointer to somewhere real, somewhere you actually own:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char* ptr = malloc(6);
    int i;

    *(ptr + 0) = 'H';
    *(ptr + 1) = 'e';
    *(ptr + 2) = 'l';
    *(ptr + 3) = 'l';
    *(ptr + 4) = 'l';
    *(ptr + 5) = 'o';

    for (i = 0; i < 6; i++)
    {
        printf("%c", *(ptr + i));
    }

    free(ptr);

    return 0;
}

If you don't point it anywhere, it points to some random place in memory which begs for a segmentation fault. If you do point it to NULL, it's null, and by definition not a real location...

And I still don't understand that why the second snippet is still working..Can you please elaborate..??

Why it works is irrelevant. Figuring out some quirk of memory mapping on the exact configuration of code, compiler, OS, hardware, and such would be a waste of effort as if anything changes the result could as well. It could also stop working at any time.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Your pointer is null. Any attempt to dereference it invokes undefined behavior. The second snippet running okay is merely bad luck because it suggests that the code isn't glaringly broken.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I guess most native English speaking people will notice that English is not my main language

If I didn't know, I wouldn't have guessed. Believe it or not, the vast majority of native English speakers are horrible at writing it. ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

However, such cases are few and far between.

Yes. I'm not advocating goto, simply adding some perspective. ;)

The goto statement is very powerful

I agree and disagree at the same time. People describe it like a jmp instruction, but goto is relatively quite restricted (even more so in C99+). The key idea is that one should use the feature needed and nothing more. In the case of goto there are more restricted constructs that do the job just as well, often more clearly, and save you the hassle of being yelled at by elitist snobs[1]. ;)

[1] One of my bigger flame attacks was when said snobs blasted me for using goto in a legitimate way and I schooled them on why I used it and why it was the best choice for the given problem. Ah, memories. :)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Laziness is certainly an issue, and sadly there's nothing we can really do about it without instating draconian policies. Another common reason for vague or poorly worded questions is non-native English speakers having trouble formulating their thoughts.

The former is obvious, and with a little practice the latter is as well. But folks in the latter category should really not be blasted for it, since they're usually trying. Language barriers can be significant.

A third reason that comes to mind is the Twitter generation shrinking their question into incoherence. For them, a simple request for more information usually helps.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

gotoxy let's you move unconditionally, but with standard output you need to print whitespace:

#include <iomanip>
#include <iostream>
#include <string>

using namespace std;

int main()
{
    int n = 15;

    cout << setfill('*') << setw(n + 1) << "\n";

    for (int i = 0; i < n - 2; i++)
    {
        cout << '*' + string(n - 2, ' ') + '*' << '\n';
    }

    cout << setfill('*') << setw(n + 1) << "\n";
}

If anything goes inside the box, care must be taken to align it properly as well as exclude whitespace characters that would otherwise be filled with non-whitespace characters. It can get kind of hairy:

#include <iomanip>
#include <iostream>
#include <string>

using namespace std;

int main()
{
    string data = "testy";
    int n = 15;

    cout << setfill('*') << setw(n + 1) << "\n";

    for (int i = 0; i < n - 2; i++)
    {
        string::size_type halfie = n / 2 - data.size() / 2 - 1;
        string x = '*' + string(halfie, ' ');

        x += data;
        x += string(halfie + (data.size() % 2 == 0), ' ') + '*';

        cout << x << '\n';
    }

    cout << setfill('*') << setw(n + 1) << "\n";
}

It can get even trickier if the data in the box could exceed the size of the box, in which you need to either make the box larger overall or truncate the data.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

he told me that most of the good programs does not use goto statement

That's not necessarily true. There's a lot of (well deserved) hate for goto, but it's not inherently broken or bad. The problem is that a lot of poorly written code has abused it in the last half decade.

There are certainly good reasons to use goto, but if you find yourself simulating a comparable control flow structure such as the various loops available, it's probably not a good use unless there's a measurable benefit.

One good rule of thumb is that if you're using goto to jump upward, it's wrong. It's go-to, not come-from, after all. ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Once again, please ask a specific question if you want a specific answer. Managing code seems pretty specific to me, so that shouldn't be a problem for you.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I think that bothers you looking at my program.

Not really, it's a minor thing. The other problem is very significant.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Congratulations! You're no longer a DaniWeb newbie.<br /> <br />

Why do people feel the need to post the contents of this notification? I'm genuinely curious.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I see two problems immediately:

char* names;

This represents an uninitialized pointer, not a pointer to infinite available character slots as you're using it. I'd strongly recommend using the std::string class instead. Otherwise you'll need to dynamically allocate memory to that pointer manually for each instance of the structure.

for(int e=20;e<0;e++){

e will never be less than 0, so this loop doesn't execute...ever.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

the console I/O library is not a standard part of C, and is associated with older (that is, pre-C99) Borland compilers.

Some common modern compilers support it. I don't see any clear indication that this is a pre-C99 compiler, though use of fflush(stdin) narrows things down a bit as well.

That said, if the compiler supports a C99 feature and doesn't use any non-C99 features, what's the problem? I can only see an issue if the code is intended to be C90 compatible.

Of larger concern is fflush(stdin), which is technically undefined behavior across the board, and use of gets, which is abhorrent regardless of compiler and non-standard as of C11.

rubberman commented: Yes, fflush() is meant for output streams. Stdin is an input stream. +13
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I was thinking about starting with how the C standard library works under the hood.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Howdy all. I've recently been considering doing an online meeting or webcast on certain subjects for which I have a lot of experience or knowledge. The idea being that something too long or complex for a Daniweb article can be more easily shown by sharing my desktop and talking about it, followed by Q&A.

However, something like this would certainly require at a minimal amount of people who are interested in joining before I put any effort into scheduling and preparing presentations. I'm thinking at least 10.

So I ask you: would you like to see a webcast of some form?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I think you can still change Items in the list.

You can. Though it's situational whether changing the type to IEnumerable<> is appropriate as it's not a comparable solution. My preference is for truly read-only properties to use ReadOnlyCollection<> or IReadOnlyList<> as it's very clear what the intention is. And for properties that don't need to be strictly read-only, IList<> or straight up List<> since the intention is still clear.

That said, 9 times out of 10 when I make a read-only list property, I change it to read-write down the road because it's unnecessarily restrictive most of the time.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Yes, of course. But for homework questions we require some substantial proof of effort on your part.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

You won't find it here, Daniweb is not a homework service. We'll be happy to help you with specific problems in your code, but we won't do your work for you.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Its like censorship.

Except not at all. Notice how none of your posts have been deleted or modified? Notice how you're still welcome to continue posting? Rest assured, I've been part of forums that do practice censorship, and Daniweb is about as far from that as I can imagine without letting spammers run rampant.

But I still cannot see who downvoted my posts/articles.

Yes, and you won't for the forseeable future. Once again, this is intentional.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

My main focus of this question is the use of objects within Interfaces, is this common practice, or even acceptable?

Your interfaces contain properties rather than objects, which is just fine and quite common.

My issue with the code is twofold:

  1. It's overly complicated for what seems to be no benefit.

  2. The interfaces appear to be there for no reason other than to use interfaces.

So you want a car class, right? Very cool. What would I do differently? Just about everything. ;) Let's go top down.

interface ITyrePressure
{
    int FrontWheel { get; set; }
    int RearWheel { get; set; }
}

An object representing pressure makes marginal sense, but the logic is inverted here. A tire has pressure, but the pressure shouldn't give two hoots about about the tire. If you're going to dig this deeply into the class structure, I'd do it more like this:

class TyrePressure
{
    private int Lo { get; set; }
    private int Hi { get; set; }
    private int Current { get; set; }

    ...
}

class Tyre
{
    private TyrePressure Pressure { get; set; }

    ...
}

The idea being some programmatic way of telling the driver that the tire pressure is too low or too high for a single tire as that's really the only thing that makes sense to me if you're going down to tire pressure granularity.

The wheel class is pointless, but yours also exhibits an inversion of data in …

ddanbe commented: Glaring mistake or not, great answer! +15
J.C. SolvoTerra commented: Great advice +3
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

There's insufficient information. Please post the relevant code, the relevant part of the file if you're using one, and the exact error as Visual Studio reports it.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

As far as I know covariance and contravariance exist in C# at least as of version 4.0.

This is true, but not for return types from methods.

ddanbe commented: Thanks for the hint! +0
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

We were taught about the var property but for some reason were told to try amd stay away from using it, ironically. Not really sure of the reasoning behind that.

var is something of a controversy. Some folks think it should never be used when optional because it hides the type of the variable. Some folks think it should always be used because it eliminates a lot of complexity and duplication of type names as well as simplifies maintenance when types change.

The middle of the road is typically to use it only when required or the type is specified on the right side of the initialization, such as

var foo = new Dictionary<int, string>();

instead of

Dictionary<int, string> foo = new Dictionary<int, string>();

whereas more opaque types would continue to specify the type as in

Dictionary<int, string> foo = LoadFoo();

rather than

var foo = LoadFoo();

My advice is to follow whatever coding standard for your organization or course, and do whatever you're most comfortable with in personal code.

On a side note, some people still believe that var is a dynamic type rather than a static type, and that's untrue. All var does is interpret the type of the initialization statement and match it when creating a variable. That type is static, so var is little more than a notational convenience in these cases.

There are situations where var is required, and that's when you're creating an anonymous …

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

There's no requirement that a DataGridView be initialized in the form Load event. Obviously you need to do it somewhere, but where kind of depends on the design of your application. Ideally it would happen in one of two places:

  1. Immediately before the user needs to see that information such as a button click event.

  2. In the background while the user is doing something else or being shown something else. This works best when the time to populate the grid is prohibitive.

Can you provide more details about the design of the application, the purpose of the grid, and how users will interact with it and its parent form?