Trying to decide which programming language I want to learn

In summary: C++ is considered a lower-level language, meaning that it is closer to the hardware and gives you more control over how your program runs. However, C# is a high-level language, which means it is easier to learn and use and has a lot of built-in libraries that make coding faster and more efficient. Both languages have their advantages and disadvantages, and it ultimately depends on what type of project you are working on. For gaming, C++ is often preferred because of its speed and control, but C# has become increasingly popular in game development as well. It's worth trying both and seeing which one you prefer working with.
  • #351
sysprog said:
The message explanation refers to what amounts to a version control problem (can't find referenced file in this version) that is entirely unrelated to anything in the .cpp code.
I know now, I had to restart my computer, now everything is fine! Strange. But thanks anyway.
 
Technology news on Phys.org
  • #352
yungman said:
I know now, I had to restart my computer, now everything is fine! Strange. But thanks anyway.
Restarting the computer resets environment variables including the global multi-path PATH variable.
 
  • #353
yungman said:
What is the best language to interface with Windows?

What is the most popular language to write pc gaming?

Thanks
The terminology is API (application program interface).
https://en.m.wikipedia.org/wiki/Application_programming_interface

For interfacing across languages, the terminology is language binding.
https://en.m.wikipedia.org/wiki/Language_binding

There are APIs for operating systems and APIs for graphics and game engines as well. What you may look at if you want to do a particular style of development is what APIs are available. Windows APIs seem to be mostly written in C or C++, but there are usually bindings for other languages to use them.
https://en.m.wikipedia.org/wiki/Lis...ication_programming_interfaces_and_frameworks

For professional game development, Unreal Engine is the most advanced engine. The best language for interfacing to that would be C++ as far as I know. https://docs.unrealengine.com/en-US/Programming/index.html.
 
Last edited:
  • Like
Likes sysprog and yungman
  • #354
Jarvis323 said:
The terminology is API (application program interface).
https://en.m.wikipedia.org/wiki/Application_programming_interface

For interfacing across languages, the terminology is language binding.
https://en.m.wikipedia.org/wiki/Language_binding

There are APIs for operating systems and APIs for graphics and game engines as well. What you may look at if you want to do a particular style of development is what APIs are available. Windows APIs seem to be mostly written in C or C++, but there are usually bindings for other languages to use them.
https://en.m.wikipedia.org/wiki/Lis...ication_programming_interfaces_and_frameworks

For professional game development, Unreal Engine is the most advanced engine. The best language for interfacing to that would be C++ as far as I know. https://docs.unrealengine.com/en-US/Programming/index.html.
Thanks so much, this is informative. I copied your reply and the links so when time comes, I will look deeper into this.

thanks
 
  • #355
I have a question about using ++, -- on an array element. I already googled error C2105, this is what I found that works. But I still have question as the Gaddis book say it's ok, but it's not.

C++:
#include <iostream>
using namespace std;
int main()
{
    int a[] = { 1, 2, 3, 4, 5 };
    int i = 0, j=0; // Second index number of the array a[]
    cout << " a[i++] = " << a[i++] << "\n\n";
    //cout << " a[0++] = " << a[0++] << "\n\n";// This doesn't work, has to be variable or literal
    cout << " a[j++] = " << a[j++] << "\n\n";// This work, using variable or const
    return 0;
}

The line in question is line 8. I put '//' in front before I can compile.
Compile error file write.jpg


Using line 9 works. This means it works if I use a variable 'j' as a[j++], but if I use a[0++], it will not compile. this is all good EXCEPT, Gaddis book is using a[0++].

So what is the problem here?

thanks
 
  • #356
yungman said:
but if I use a[0++], it will not compile.
How do you think the compiler should interpret that?

yungman said:
this is all good EXCEPT, Gaddis book is using a[0++].
I don't have that book but I'm pretty sure the closing ] is in a different place.

Also, as I think has been mentioned before in this thread (although it is hard to keep track over 355 posts), a[j++] is a good way to get into a mess even if you know what you are doing.
 
  • Like
Likes sysprog
  • #357
pbuk said:
How do you think the compiler should interpret that?I don't have that book but I'm pretty sure the closing ] is in a different place.

Also, as I think has been mentioned before in this thread (although it is hard to keep track over 355 posts), a[j++] is a good way to get into a mess even if you know what you are doing.
Thanks for the reply. I am just following the book to learn. I do think it's kind of strange to advance to another element of the array this way.

No, I did not put the ++ in the wrong place, I took that part out of the program before I post to make it simpler.

Yes, I would avoid using arr[j++] that really doesn't made much sense to use when it's so easy to just do j=j+1 or something.
 
  • #358
++i means increment i and then evaluate the expression. i++ means evaluate the expression and then increment i. 0++ would mean evaluate the expression then increment 0. But 0 is temporary; after the expression is evaluated that instance of 0 doesn't exist anymore, so there is nothing to increment.

The rule to remember is ++ before means increment before, and ++ after means increment after.
 
  • Like
Likes sysprog
  • #359
Can you please quote more of what you're saying about what Gaddis said?
 
  • Like
Likes pbuk
  • #360
what is the number and name of the section in Gaddis? I see in my copy where he decrements and increments array indices, but I don't see the problem you are referring to

Also, 0 is a number and cannot be incremented nor decremented, only variables can
 
  • Like
Likes sysprog and pbuk
  • #361
Dr Transport said:
what is the number and name of the section in Gaddis? I see in my copy where he decrements and increments array indices, but I don't see the problem you are referring to

Also, 0 is a number and cannot be incremented nor decremented, only variables can
I was WRONG, I am going too fast, I thought I read it. The book only do arr[count++] which is of cause work. Somehow I took it that I can do arr[0++] and wasting a lot of time.

Thanks guys for looking into this, it's all my fault.

Maybe I should slow down, I have been working on this 5 to 6 hours a day. I might be seeing things! But I am really learning. I started completely over from Chapter 1 when I got the Gaddis book, I covered 7 chapters in like 2 weeks.
 
  • #362
yungman said:
I was WRONG, I am going too fast, I thought I read it. The book only do arr[count++] which is of cause work. Somehow I took it that I can do arr[0++] and wasting a lot of time.

Thanks guys for looking into this, it's all my fault.

Maybe I should slow down, I have been working on this 5 to 6 hours a day. I might be seeing things! But I am really learning. I started completely over from Chapter 1 when I got the Gaddis book, I covered 7 chapters in like 2 weeks.
I'm sure that you'll recognize that when you read a good textbook and something in it seems to you to be wrong, it's ok to suspect yourself ahead of suspecting its author; in this case that's especially so, given that a Foreword for the Gaddis book was written by @Mark44, as he mentioned earlier in this thread, when you first mentioned Gaddis.
 
Last edited:
  • Sad
Likes pbuk
  • #363
Please learn from this experience; your mistake was not misreading something from the book, anyone can do that, your mistake was not going back and checking when I pointed out that a[0++] was nonsense.

Also, I often find that an apology is better received than an admission of error.
 
  • #364
pbuk said:
yungman said:
but if I use a[0++], it will not compile.
How do you think the compiler should interpret that?
I think that it should take it as meaning let 0 equal 1, and should then respond "I'm sorry, Dave; I'm afraid I can't do that.", which it pretty much did.

 
  • Haha
Likes atyy, Jarvis323, Dr Transport and 1 other person
  • #365
yungman said:
Yes, I would avoid using arr[j++] that really doesn't made much sense to use when it's so easy to just do j=j+1 or something.
No, it really does make sense, because you can write arr[j++] and save the step where you increment j with a separate assignment.
sysprog said:
given that a Foreword for the Gaddis book was written by @Mark44, as he mentioned earlier in this thread,
No, I didn't write a foreword -- I was just one of many reviewers of the First Edition.
 
  • #366
Mark44 said:
No, I didn't write a foreword -- I was just one of many reviewers of the First Edition.
Oops, sorry, @Mark44 ##-## I mis-recalled what you had said about that.
 
  • #367
Mark44 said:
No, it really does make sense, because you can write arr[j++] and save the step where you increment j with a separate assignment.
My idea of a good program is clean, easy to understand, straight forward rather than saving one line. Makes no difference in real world whether the program is 20 lines or 21 lines.
 
Last edited:
  • Like
Likes pbuk
  • #368
yungman said:
My idea of a good program is clean, easy to understand, straight forward rather than saving one line. Makes no difference in real world whether the program is 20 lines or 21 lines.
That attitude won't help you to win a code golf greenbar jacket.
 
  • #369
yungman said:
My idea of a good program is clean, easy to understand, straight forward rather than saving one line. Makes no difference in real world whether the program is 20 lines or 21 lines.
Code should generally be easy to understand, but the increment and decrement operators are idioms of C and C++ that you should learn.

In the real world, it sometimes does make a big difference when you use one line of code instead of two, especially in loops that run a large number of times.
 
  • #370
Jarvis323 said:
i++ means evaluate the expression and then increment
The C / C++ standard for i++ is to make a local copy of i, increment i, then use the local copy made before i was incremented in the expression. An example of where this makes a difference (this is used in an linked list iterator based merge to move nodes within a list):

Code:
    std::list<...> &ll                    // link list
    std::list<...>::iterator li           // left iterator
    std::list<...>::iterator ri           // right iterator
    // ...
            ll.splice(li, ll, ri++);      // move node from ri to just before li
Since ri is incremented before the node is moved, ri ends up pointing to the next node after ri before the splice to move the node. If ri was incremented afterwards, then ri would end up pointing to the node at li before the spice to move the node. The sequence in this case is: create a copy of ri, increment ri, call ll.splice using the copy of ri before it was incremented.

For the other issue, I'm thinking typo somewhere and it should be a[0]++ .
 
  • Informative
Likes Jarvis323
  • #371
yungman said:
My idea of a good program is clean, easy to understand, straight forward rather than saving one line. Makes no difference in real world whether the program is 20 lines or 21 lines.
You are absolutely right about this @yungman, code that is quicker to type but harder to debug and maintain is bad code.
Mark44 said:
Code should generally be easy to understand, but the increment and decrement operators are idioms of C and C++ that you should learn.
This is also true, and part of that learning is understanding how to use them to write code that is easy to understand and maintain.
C:
// Easy to understand and maintain:
a[i] = c;
i++;

// Harder to understand and maintain:
a[i++] = c;

Mark44 said:
In the real world, it sometimes does make a big difference when you use one line of code instead of two, especially in loops that run a large number of times.
For that to be significant in a particular situation you would have to know that
  1. the harder-to-maintain code does actually provide a performance gain; and
  2. the cost of harder-to-maintain code is outweighed in this particular situation by the value gained by performance improvement
1. can be found by experiment. I'll offer a prize for the first person to show that the compiled code for the second example above (using any sensible compiler settings and target CPU) runs any faster.

I have only ever experienced 2 to be true in system code (e.g. device drivers) and in computational libraries, never in application code.
 
  • Like
Likes yungman
  • #372
sysprog said:
That attitude won't help you to win a code golf greenbar jacket.
Sorry if I offended you. I think I have been very courteous, thank anyone that helps me and give Like to anyone that helps me. This is something that I hold close to my heart in my decades of being a senior EE and manager of EE. Always pick the most straight forward and easy to understand way to design even in hardware, analog, RF circuits designs. It's very important because nobody is staying in the same job forever, someone else has to jump in and maintain the project. The goal is to make it easy for someone to pick it up and continue the work in real life working environment. I think this is much more important in programing as people work in groups. Whenever there is a problem and someone has to troubleshoot it, it's good to have programs that are easy to understand and straight forward.

I remember when I was a junior programmer 40 years ago, one of the contract programmer was fired and and all his work was thrown in the garbage can right after he left. This was because he kept poor documentations and nobody understand what he was doing. They rather started over. This is a true case in Aiden Energy Div. in Palo Auto back in 1979 when I was there.

Actually I was on EE forum here a few years back helping people, that's why I racked up 4500 posts here. While I am here getting help on C++ now, I also go there to try to help to give back to the forum. But seems like the forum is very slow compare to the days I frequented the EE forum.. this is the first time I actually ask for help in PF.
 
Last edited:
  • #373
Comment the first: it's the programmer's job to write understandable code; it's the compiler's job to turn that into efficient code. Where to put increment instructions is an example of something a compiler is very good at, and it's a waste of energy to try and out-optimize the compiler by clever positioning of an increment instruction.

Comment the second: "understandable code" does not mean "avoid idiomatic constructs of the language". Like it or not, j++ is an idiom of C. Using j=j+1 is taste at best; don't kid yourself to think it's better. That would be like speaking English without contractions.

Comment the third: a[j++] specifies exactly when j is to be incremented. It is thus not identical to j=j+1. Indeed, for reasons that at the time made a lot of sense, I once wrote something like b = function_a(i) + function_b(++i). While that can be done with an i=i+1 in there, it breaks up the logic flow.
 
  • Like
Likes sysprog
  • #374
sysprog said:
I think that it should take it as meaning let 0 equal 1

I believe some Lisp machines let one redefine zero. This was seldom as good an idea as it sounded.
 
  • #375
Vanadium 50 said:
a[j++] specifies exactly when j is to be incremented.
For the example code below, regardless of the order add2sum(j)+add2sum(j++) or add2sum(j++)+add2sum(j), Visual Studio will call the instance of add2sum with j++ first, resulting in k = 1 + 3 == 4. This is due to the fact that C / C++ doesn't specify the order of evaluations of expressions (including function calls), so the compiler is free to evaluate in any order, in this case choosing to always call the instance of add2sum(j++) first, regardless if it is on the left or right. Some other languages specify an order of evaluation (for example, APL is right to left unless overridden with parenthesis).

Code:
#include <stdio.h>
static int sum = 0;
int add2sum(int i)
{
    sum += i;
    return sum;
}
int main(int argc, char**argv)
{
int j = 1;
int k;
    k = add2sum(j)+add2sum(j++);   // doesn't matter if the j++ is 1st or 2nd call
    printf("%d\n", k);             // k == 4
    return(0);
}
 
  • Informative
Likes Jarvis323
  • #376
Mark44 said:
In the real world, it sometimes does make a big difference when you use one line of code instead of two, especially in loops that run a large number of times.
pbuk said:
For that to be significant in a particular situation you would have to know that
  1. the harder-to-maintain code does actually provide a performance gain; and
  2. the cost of harder-to-maintain code is outweighed in this particular situation by the value gained by performance improvement
I'm very much not a fan of difficult-to-maintain code, but in certain rare instances its use is justified. Any such uses should be well-documented via code comments.

With regard to item 2 above, I've written assembly code (using AVX-512 instructions) that outperforms optimized C code. The code, both C and assembly, iterates through fairly large arrays of floats and picks out all of the array elements that are larger than some specified value. I've timed both code chunks, and my assembly code runs faster than the C code, even when the C code is fully optimized for speed.

Compilers usually produce well-optimized code, but if you know what you're doing, you can sometimes write code that is faster.
 
  • Like
Likes sysprog
  • #377
yungman said:
Sorry if I offended you.
Thanks for that, but please Sir, I didn't mean to suggest that I had taken offense; you said,
yungman said:
My idea of a good program is clean, easy to understand, straight forward rather than saving one line. Makes no difference in real world whether the program is 20 lines or 21 lines.
and I replied to that with:
sysprog said:
That attitude won't help you to win a code golf greenbar jacket.
That was on my part an attempt at being wry ##-##'code golf' is a programmers' game in which coders compete to accomplish something using the fewest lines or fewest characters, analogous to golfers winning by getting the ball in the hole using the fewest strokes; the 'green jacket' is a golf award inclusive of an actually wearable green jacket; my reference to a "greenbar jacket" for code golf winners was a reference to greenbar line printer paper that uses two light shades of green, one rather darker than the other but both much lighter (hopefully) than the black printer ink, to make a printout easier to pick out groups of a few print lines in ##-## if there isn't really such a thing as a similarly shaded greenbar jacket, well then I propose that there should be for code golf winners ##-##
 
Last edited:
  • #378
Mark44 said:
I'm very much not a fan of difficult-to-maintain code, but in certain rare instances its use is justified. Any such uses should be well-documented via code comments.

With regard to item 2 above, I've written assembly code (using AVX-512 instructions) that outperforms optimized C code. The code, both C and assembly, iterates through fairly large arrays of floats and picks out all of the array elements that are larger than some specified value. I've timed both code chunks, and my assembly code runs faster than the C code, even when the C code is fully optimized for speed.

Compilers usually produce well-optimized code, but if you know what you're doing, you can sometimes write code that is faster.
I think that @Mark44's PF Insights articles on the use of the Intel AVX-512 architecture are the best guides on that topic that I could find.
 
  • Like
Likes Mark44
  • #379
Mark44 said:
I'm very much not a fan of difficult-to-maintain code, but in certain rare instances its use is justified. Any such uses should be well-documented via code comments.

With regard to item 2 above, I've written assembly code (using AVX-512 instructions) that outperforms optimized C code. The code, both C and assembly, iterates through fairly large arrays of floats and picks out all of the array elements that are larger than some specified value. I've timed both code chunks, and my assembly code runs faster than the C code, even when the C code is fully optimized for speed.

Compilers usually produce well-optimized code, but if you know what you're doing, you can sometimes write code that is faster.
Completely agree - if you really need to speed up a tight loop then providing you are willing to restrict your target processor then assembly is the way to go. With a device driver this is always the case, although with say a numerical analysis routine you might want portability so some horrible, hacky (but well commented) c code is indeed best.

However none of this applies for routine use of a[i++]. In fact I have done some experimenting and you might be surprised to find that this quick-to-type shortcut can actually produce SLOWER code!

Edit: as well as being off-topic what follows is original research but I hope it will be allowed to remain as a point of interest. Probably best not to follow up here though!

Source code (simple Fibonnaci sequence):
#include <iostream>
using namespace std;
int main() {
  int a[100] = {0, 1};
  int k = 2;
  int f_k_minus_1 = 1;
  int f_k_minus_2 = 1;
  int f_k;
  while (f_k < 1000) {
    f_k = f_k_minus_1 + f_k_minus_2;
    f_k_minus_2 = f_k_minus_1;
    f_k_minus_1 = f_k;
    // Either (bad):
    a[k++] = f_k;
    // Or (good):
    // a[k] = f_k;
    // k++;
  }
  cout << a[k - 1];
  return 0;
}

Compiled using g++ -S (i.e. no optimisation) g++ version 7.5.0 on x86_64
The generated code saves all intermediate results to memory. The 'bad' code uses an additional register for the incremented value of k which it then saves to memory.
Using a[k++]:
        movl    -432(%rbp), %eax        ; Load k into ax.
        leal    1(%rax), %edx           ; Load k + 1 into dx.
        movl    %edx, -432(%rbp)        ; Save dx into k.
The 'good' code simply increments k in place. This saves an instruction but adds an additional fetch from (cached) memory to reload k into the ALU.
Using a[k]; k++:
        movl    -432(%rbp), %eax        ; Load k into ax.
        ; do some other stuff.
        addl    $1, -432(%rbp)          ; Add 1 to k;

Compiled using g++ -S -O g++ version 7.5.0 on x86_64
Now the compiler is not worried about an informative core dump for debugging it uses registers for all intermediate values and comes up with almost the same object code for both 'good' and 'bad' sources - but separating the increment from the array indexing still saves 1 instruction, although only on the first iteration of the loop. This time I am going to show the whole loop for each case.
Using a[k++]:
.L3:
        leal    (%rsi,%rcx), %edx
        movl    %eax, %edi
        movl    %edx, -4(%rsp,%rax,4)
        addq    $1, %rax
        movl    %ecx, %esi
        movl    %edx, %ecx
        cmpl    $999, %edx
        jle     .L3
Using a[k]; k++:
        jmp     .L3
.L6:
        movl    %edx, %ecx
.L3:
        leal    (%rcx,%rsi), %edx
        movl    %edx, -4(%rsp,%rax,4)
        movl    %eax, %edi
        addq    $1, %rax
        movl    %ecx, %esi
        cmpl    $999, %edx
        jle     .L6
Conclusion: a[i++]; may be quicker to type but is harder to maintain and may well run slower than a[i]; i++;.
 
Last edited:
  • Like
Likes sysprog
  • #380
I wouldn't be surprised if a c compiler accepted, and processed properly, something to the effect of a[0++], but it also wouldn't surprise me if it didn't : since the 0 is procedure-embedded, that's explicitly "self modifying code", might give a run-time OS hissy-fit. And, it might preclude an optimizer from reserving and using a register, which would be faster.

You could always split the difference :
register int i=0 ; ...a[i++] ;
 
  • #381
sysprog said:
Thanks for that, but please Sir, I didn't mean to suggest that I had taken offense; you said,
and I replied to that with:
That was on my part an attempt at being wry ##-##'code golf' is a programmers' game in which coders compete to accomplish something using the fewest lines or fewest characters, analogous to golfers winning by getting the ball in the hole using the fewest strokes; the 'green jacket' is a golf award inclusive of an actually wearable green jacket; my reference to a "greenbar jacket" for code golf winners was a reference to greenbar line printer paper that uses two light shades of green, one rather darker than the other but both much lighter (hopefully) than the black printer ink, to make a printout easier to pick out groups of a few print lines in ##-## if there isn't really such a thing as a similarly shaded greenbar jacket, well then I propose that there should be for code golf winners ##-##
Ha ha, you got me. I don't know anything about golf. the closest thing I was to golf was my grandson want to see how's the inside of golf balls looked like, so I bought one and cut it open!

I know there are people particular in class that jump through hoops to get rid of one or two lines in coding, going through all the network theorems in electronics to save a few components. That's good in the class, but not necessary in the real world. I actually had a debate on the EE forum here a week or so ago that I am an advocate that I work hard to make all my design as simple as possible so people see understand and predict all the current and voltages just with simple V=IR. That if you have to use network theorem to find the voltages and current, that's too complicated. Of cause, one cannot avoid that completely, but at least make an afford to keep it straight forward. For both maintenance and documentation. Be ingenious in the whole system, not the every little circuit(in this case, the code lines).

I have no issue using i++ or ++i type of post and pre increments. Where I draw the line is array[i++]. You have to look around to find the value of "i" to know the number already. Then you have to think about it's not the array you are looking, you have to look at array[i+1]. Never mind it's harder for others to look at. hell, at my old age, I likely get tripped if I look at the program 2 weeks later! That's old age for you!
 
  • Like
Likes pbuk
  • #382
hmmm27 said:
wouldn't be surprised if a c compiler accepted, and processed properly, something to the effect of a[0++]
I would be very surprised to find any C compiler that accepted this. A constant is not an l-value, so can't be assigned to or incremented or otherwise treated like a variable.
 
  • Like
Likes pbuk and sysprog
  • #383
yungman said:
Be ingenious in the whole system, not the every little circuit(in this case, the code lines).
As far as program optimization is concerned, that's pretty much the opposite of good advice. For optimization, there's the 80-20 rule: 20% of the program takes 80% of the time.

Of course you want to write good code, but you never want to optimize the entire program -- just the part that's most active. And that's exactly what profilers are good for.
yungman said:
Where I draw the line is array[i++]. You have to look around to find the value of "i" to know the number already. Then you have to think about it's not the array you are looking, you have to look at array[i+1].
No. You have this all wrong.
To evaluate array[i++], you just need to know array[ i]. The index i gets incremented after it is used as the index.

For example, if i == 1, and the array is initialized with {2, 4, 6}, then array[i++] == 4. Sometime after that, i gets incremented to 2.

On the other hand, if i == 1, then i is incremented to 2, so array[++i] == 6.

This ain't rocket science.
 
  • Like
Likes sysprog
  • #384
I have questions with this reading numbers from file and write into vector and display the numbers.
C++:
// Read content of file to array
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;

//void getNum(int arr[], int size);
ifstream inFile;
int main()
{

    int count = 0;
    int num;
    int x = 0;
    vector<int>dynArr(3);
    inFile.open("C:\\Users\\alanr\\Desktop\\C++ exercise\\Gaddis\\inout files\\array1.txt");
    if (inFile.fail())
    {
        cout << " Fail to open file\n\n";
    }
    else
    {
        while (inFile >> num)
        {
            //cout << num << " ";
            dynArr.push_back(num);// Read from file and write to vector num.
        }
        cout << " going to read dynArr\n\n";
        while (!dynArr.empty())
        {
            num = dynArr[x];
            cout << num << " ";// display all the numbers until the end.
            x++;
        }
    }
    cout << "\n\n";
    return 0;
}

It kind of doing what I want, BUT there's a warning as shown when I ran the program that the vector is out of bound.
Compile error file write.jpg


It's only defined as 3 element vector, small and I only read in 5 numbers. It cannot be out of bound!Also if you look at line 32 of the code and look at the top left corner of picture above, I expect to display 12345. But I got 00012345. AND the 12345 is at the right side of the stream. Is it when I use dynArr.push_back, I pushed the 5 numbers AFTER the 3 empty elements? That's the reason I got 000 in front?

Bottom line, I am not sure whether I did it right. I am pushing my knowledge on this one.
I read from file that has 5 numbers( I already verify I can do it with 3 numbers, 6 numbers).
1) I use ( inFile.fail()) to check for EOF. Then read the numbers one by one into a variable num, then write into the vector dynArr using dynArr.push_back(num);

2) I use (!dynArr.empty()) to read until I reach the end of the dynArr.

I want to know whether I am doing all these correctly. I am putting a lot of effort in data management, from files to vectors etc. I just feel this is very important in programing instead of just condition statements or loop statements. I want to use dynArr.pop_back next to control the size of the vector. To me, these data management is a lot more difficult.

Thanks
 
Last edited:
  • #385
Vanadium 50 said:
Comment the first: it's the programmer's job to write understandable code; it's the compiler's job to turn that into efficient code. Where to put increment instructions is an example of something a compiler is very good at, and it's a waste of energy to try and out-optimize the compiler by clever positioning of an increment instruction.
Completely agree.

Vanadium 50 said:
Comment the second: "understandable code" does not mean "avoid idiomatic constructs of the language". Like it or not, j++ is an idiom of C. Using j=j+1 is taste at best; don't kid yourself to think it's better. That would be like speaking English without contractions.
Agree with reservations - I would say that understandable code includes "be careful that you do not use idiomatic constructs in a way that hides their potential side effects"

Vanadium 50 said:
Comment the third: a[j++] specifies exactly when j is to be incremented.
Completely disagree. Look at the following:
C:
// The timing of the increment is unspecified. 
b = a[j] + a[j++] 
// In a c++17 implementation the value of a[0] is copied into a[2], in earlier standards
// it is either copied into a[1] or the operation may be unspecified.  
j = 0;
a[j + 1] = a[j++]
https://en.cppreference.com/w/cpp/language/eval_order

Vanadium 50 said:
Indeed, for reasons that at the time made a lot of sense, I once wrote something like b = function_a(i) + function_b(++i).
You are lucky that worked; recompile it and there is no guarantee it still will. https://en.cppreference.com/w/cpp/language/eval_order
Order of evaluation of any part of any expression, including order of evaluation of function arguments is unspecified (with some exceptions listed below). The compiler can evaluate operands and other subexpressions in any order, and may choose another order when the same expression is evaluated again.

There is no concept of left-to-right or right-to-left evaluation in C++.
A way to write this that is guaranteed to work is:
C:
b = function_a(i) + function_b(i + 1);
i++; // Some people prefer ++i here; the compiler shouldn't care.
Or alternatively:
C:
c = function_a(i);
i++; // Some people prefer ++i here; the compiler shouldn't care.
b = c + function_b(i);
 
Back
Top