• Hey, guest user. Hope you're enjoying NeoGAF! Have you considered registering for an account? Come join us and add your take to the daily discourse.

Programming |OT| C is better than C++! No, C++ is better than C

Okay I realize what I'm doing can hardly be called programming as I merely make a batch-file but I figured it's still the best thread to ask in :p Basically what I try to do after the recent WebM boom is to make a batch-file that converts videos to WebM and then place it in Windows' "Send To" context menu so it's easily accessible.

I already got the batch file up and fully working though I have one problem. It works when I drag and drop a video-file onto the .bat that is in the same directory as the .bat itself, though I get a "File not found" error when I drag and drop a file from outside the .bat's directory. Is what I want to do even possible?

Here's the content of my .bat file so far:

Code:
@echo off
echo "Specify starting time in hh:mm:ss[.mss] (for example 00:00:10.000 would equal 10 seconds into the video)"
set /p Start=

echo "Specify end time in hh:mm:ss[.mss] (for example 00:00:20.000 would equal 20 seconds into the video)"
set /p End=

echo "Specify the width of the WebM in pixels (the height will be calculated automatically to maintain the aspect ratio)"
set /p Width=

echo "Set the maximum allowed bitrate (default is 15000)"
set /p Bit=

ffmpeg -i %1 -ss %Start% -to %End% -c:v libvpx -crf 4 -b:v %Bit%K -vf scale=%Width%:-1 -an %1.converted.webm

Thanks in advance for any help!

EDIT: Figures I solve the problem on my own minutes after posting this :p

I thought "File not found" was related to the .bat not finding the dragged and dropped video-file but I just had to specify the absolute path to ffmpeg.exe and it's working, oh well...
 

squidyj

Member
welcome to the awesome world of openGL :) it's hard to help you debug without the rest of the program, it could also be a factor of running on a VM, what kind of GPU access it has or if it's using MESA. have you done the obvious of starting with 'clean' shaders and adding the features in in order? ie. get the fragments on, add lighting, add textures instead of trying to get it all to work at once. also do you have shader compile errors output?

Right now I'm no longer running in a VM, I managed to get glew linking properly in windows with minGW from QT Creator (remind me never to trust the qt-creator library finder helper thing, it doesn't seem to realize that minGW is more than happy to take libglew32.a and keeps thinking it wants a .lib file)

Here's a pastebin with the most relevant portions of c++ code. I have a couple of glUniformMatrix4fv calls outside of here to update my view and projection matrices but other than that this is all my opengl calls. It's rather long so I'm putting it in a pastebin instead of spamming in here.

I also worked up my shaders from rendermonkey where they are working beautifully, you can see them at the end.

Also I might add that this entire experience might be far less frustrating if the opengl.org website wasn't down for an ENTIRE FUCKING WEEK, WHAT THE FUCK?

http://pastebin.com/0TuaCLkS
 

Kyuur

Member
Can anyone tell me if there is any difference between the following code in C++?

Code:
myClass foo(params)

Code:
myClass foo = myClass(params)

My IDE only seems to bring up parameters when I use the second method, but both seem to do the job. Most of the examples I find, on the other hand, use the first. I tried googling for an answer, but I'm not exactly sure how to word the question.

Edit: Answer here: http://stackoverflow.com/questions/2722879/calling-constructors-in-c-without-new
 

tokkun

Member
Can anyone tell me if there is any difference between the following code in C++?

Code:
myClass foo(params)

Code:
myClass foo = myClass(params)

My IDE only seems to bring up parameters when I use the second method, but both seem to do the job. Most of the examples I find, on the other hand, use the first. I tried googling for an answer, but I'm not exactly sure how to word the question.

-The first one will call the constructor myClass(parameters) to create foo.
-For the second one, I believe it will call myClass(parameters) to create the r-value, then call either the Copy (pre-C++11) or Move (post-C++11) constructor to create foo from the r-value.

The rules for when copy constructors are called can get confusing and hard to remember, so if you want to be sure, you can try disabling the default generated copy constructor and see what happens.
 

Slavik81

Member
Can anyone tell me if there is any difference between the following code in C++?

Code:
myClass foo(params)

Code:
myClass foo = myClass(params)

My IDE only seems to bring up parameters when I use the second method, but both seem to do the job. Most of the examples I find, on the other hand, use the first. I tried googling for an answer, but I'm not exactly sure how to word the question.
The first creates an object named 'foo' initialized with the constructor that takes params.
The second creates two objects. One is a temporary object initialized with the constructor that takes params. The other object is named 'foo' and is copy-constructed or move-constructed from the temporary object, depending on if the compiler and the type support move-construction.
 

nillapuddin

Member
Ive been out of the web design/programming scene for about 2 years, and only have about 2 years of full on experience

Im about to start on a very ambitious project (which is kinda sorta absolutely) over my head, but Im going to do my best to self teach alot of the methods and catch up.

I was hoping some of yall might be kind enough to shoot me in the right direction.

Essentially Ill be creating a section of an existing commercial website

The purpose being to dynamically show variations of a single product.

Ex: Red shutters on a house *drop down menu, click* Blue shutters *drop down* Grey shutter, etc

Ive spent the first part of the day looking at some very interesting examples of image manipulation, doing my best to learn about (everything), among other resources.

Any advice on a solid starting point?
Id greatly appreciate it, Ill try to check back and give feedback soon as I can, Ive got about 15 tabs open trying to catch up on the world since 2011 (including things from OP obviously, just trying to sort through it all).
 

squidyj

Member
spend a week trying to get it working on my laptop, 10 minutes on my desktop and it's mostly correct, some inverted tangent spaces it seems.
 
Right now I'm no longer running in a VM, I managed to get glew linking properly in windows with minGW from QT Creator (remind me never to trust the qt-creator library finder helper thing, it doesn't seem to realize that minGW is more than happy to take libglew32.a and keeps thinking it wants a .lib file)

Here's a pastebin with the most relevant portions of c++ code. I have a couple of glUniformMatrix4fv calls outside of here to update my view and projection matrices but other than that this is all my opengl calls. It's rather long so I'm putting it in a pastebin instead of spamming in here.

I also worked up my shaders from rendermonkey where they are working beautifully, you can see them at the end.

Also I might add that this entire experience might be far less frustrating if the opengl.org website wasn't down for an ENTIRE FUCKING WEEK, WHAT THE FUCK?

http://pastebin.com/0TuaCLkS


i know it's been driving me mental as well, but you can still access the cached pages from google search.

i'll have a poke around at it later today and see what comes out.

edit: just saw your second post, working then?
 
This was very interesting to read. Thanks for sharing.

edit: I was kinda surprised by how little had to change for them to fix this. Is there anything else they have to do to plug the security hole after this is pushed out?

From what I understand, that's really the extent of the patch. The full diff is here, and there's a few other minor changes:

http://git.openssl.org/gitweb/?p=openssl.git;a=commitdiff;h=96db9023b881d7cd9f379b0c154650d6c108e9a3

It's amazing how a failure to do a simple bounds check can cause such a huge security vulnerability.
 

Granadier

Is currently on Stage 1: Denial regarding the service game future
From what I understand, that's really the extent of the patch. The full diff is here, and there's a few other minor changes:

http://git.openssl.org/gitweb/?p=openssl.git;a=commitdiff;h=96db9023b881d7cd9f379b0c154650d6c108e9a3

It's amazing how a failure to do a simple bounds check can cause such a huge security vulnerability.

Yeah, I took a look at the source changes and was surprised as well by how little changed.

I sort of understand the changes here to ensure that the package is the right length:
Code:
-/* Read type and payload length first */
-       hbtype = *p++;
-       n2s(p, payload);
-       pl = p;

+       /* Read type and payload length first */
+       if (1 + 2 + 16 > s->s3->rrec.length)
+               return 0; /* silently discard */
+       hbtype = *p++;
+       n2s(p, payload);
+       if (1 + 2 + payload + 16 > s->s3->rrec.length)
+               return 0; /* silently discard per RFC 6520 sec. 4 */
+       pl = p;
But what does the change from "3 + payload + padding" to "write_length + payload + padding" do?
Code:
-               buffer = OPENSSL_malloc(1 + 2 + payload + padding);
+               buffer = OPENSSL_malloc(write_length);
when "write_length" is essentially just equal to "3 + payload + padding"
Code:
+               unsigned int write_length = 1 /* heartbeat type */ +
+                                           2 /* heartbeat length */ +
+                                           payload + padding;
 
welp... discovered a defect in my code where i didn't return out of a method for a daily schedule thread and it always went to a runtime exception (which isn't logged). It went straight past QA because the thing worked one time... but never again. they only checked for 1 time >.<
 

Water

Member
Can anyone tell me if there is any difference between the following code in C++?

Code:
myClass foo(params)

Code:
myClass foo = myClass(params)

My IDE only seems to bring up parameters when I use the second method, but both seem to do the job. Most of the examples I find, on the other hand, use the first. I tried googling for an answer, but I'm not exactly sure how to word the question.

Edit: Answer here: http://stackoverflow.com/questions/2722879/calling-constructors-in-c-without-new
The first line is vulnerable to the "most vexing parse" problem, while the second has needless repetition of the type (consider if "myClass" was "std::map<unsigned, std::vector<float>>" or something...), and both lines risk doing an accidental type conversion. If you use modern C++, you should avoid those problems by using either of these forms most of the time:
Code:
myClass foo{params};
auto foo = myClass{params};
 

squidyj

Member
i know it's been driving me mental as well, but you can still access the cached pages from google search.

i'll have a poke around at it later today and see what comes out.

edit: just saw your second post, working then?

Well, I was trying out various schemes for passing my data into the shader
including layout(location = n) which spat back errors at me. SO I decided I'd grab my code and set up my shit on my desktop and see what happens, after resolving all the required libraries and tweaking the code I have a shader program that executes properly.

I think all I have to do now is nail down what looks to be some sort of logic bug on my part and add some camera controls and ui elements.

I might as well throw the logic bug into the ring. My application is simply an implementation of parallax mapping (with offset limiting, it's like one instruction less than base parallax mapping). Which if anyone doesn't know is an extension to normal mapping where you additionally provide a height map. you sample the height map in your fragment shader to determine how much higher or lower the the actual surface is then compute an offset (based on your viewing vector in tangent space) to your texture coordinate where and then you sample the rest of your textures and go on your merry way.

The problem is that the parallax offset is in the opposite direction of what it should be on one axis for 5 of the 6 faces.

This suggests to me a problem with my computation of the tangent vector. The original texcoord is correct, it seems that the viewing direction is simply sometimes mirrored from what it ought to be on either the x or y axis meaning that the tangent vector is negative

Tangent calculation. Note that once this is correct I intend to calculate the bitangent/binormal here, possibly just passing the completed matrix in as input instead of
the one vector
Code:
void calcTangent(vector<Vertex> &verts, int n1, int n2, int n3)
{
    Vertex &v1 = verts[n1];
    Vertex &v2 = verts[n2];
    Vertex &v3 = verts[n3];

    vec2 UV1 = v2.texCoord - v1.texCoord;
    vec2 UV2 = v3.texCoord - v1.texCoord;

    float f = 1.0 / (UV1.x * UV2.y - UV1.y * UV2.x);

    vec3 E1 = v2.position - v1.position;
    vec3 E2 = v3.position - v1.position;

    vec3 tangent = f * (UV2.y * E1 - UV1.y * E2);
    vec3 bitangent = f * (UV1.x * E1 - UV2.x * E2);

    v1.tangent += tangent;
    v2.tangent += tangent;
    v3.tangent += tangent;
}

Vertex Shader. All of the conversions to tangent space occur here. as vertex attributes, normal and tangent are stored as unit vectors so normalization is not required
Code:
uniform mat4 MV;
uniform mat4 P;
uniform mat3 NML;
uniform vec3 lPos;
uniform vec3 eye;

out vec2 texCoord;
out vec3 vDir;
out vec3 lDir;
out vec3 tang;
layout(location = 5) in vec3 position;
layout(location = 6) in vec3 normal;
layout(location = 7) in vec2 vTexCoord;
layout(location = 8) in vec3 tangent;

void main()
{
   vec4 pos = MV * vec4(position,1);
   gl_Position = P * pos; 
   texCoord = vTexCoord;

    vec3 cam = vec3(0, 0, 3);
   vec3 V  = -pos.xyz;
   vec3 L = lPos - pos.xyz;

   vec3 norm = NML * normal;
   vec3 tan = NML * tangent;
   vec3 bin = cross(norm, tan);
    //uses dot products instead of constructing BTN matrix
   vDir.x  = dot(tan, V);
   vDir.y  = dot(bin, V);
   vDir.z  = dot(norm, V);

   lDir.x  = dot(tan, L);
   lDir.y  = dot(bin, L);
   lDir.z  = dot(norm, L);
}

I'm happy to be moving on to something a little more easily testable and tangible but I'm super worn out after wrestling with that other shit for so long :l


Edit: Oh hey, where's the part where I calculate handedness? the thing that would exactly cause my problem above? trololololol :p
 

Lucius86

Banned
Fellow gaffers - I need some help with my programming. I've asked the question over at Stack Overflow, but wondering if any of you guys and girls could help.

Put simply, I am using Visual Studio C# to create a Windows Phone app, but it could also apply for Windows 8. The following is in XAML.

<toolkit:ListPicker x:Name="defaultPicker"
SelectedIndex="{Binding Source={StaticResource appSettings}, Path=LanguageSetting, Mode=TwoWay}"
Grid.Column="2" Grid.Row="5">
<toolkit:ListPickerItem Content="Cesky"/>
<toolkit:ListPickerItem Content="English"/>
<toolkit:ListPickerItem Content="Deutsch"/>
</toolkit:ListPicker>

With this code I create a ListPicker - am pull down box. The SelectedIndex field relates to my IsolatedStorage - my saved settings for my app. When I select an option, it saves the result much like how a ListBox does - but when I leave the age and return back, the default SelectedItem does not change to the value the user set previously.

I want this so it is persistent. Any value I put in for SelectedItem returns compile errors. How can I make this happen?

Feel good points helping a newbie app developer is on offer.
 

phoenixyz

Member
But what does the change from "3 + payload + padding" to "write_length + payload + padding" do?
Code:
-               buffer = OPENSSL_malloc(1 + 2 + payload + padding);
+               buffer = OPENSSL_malloc(write_length);
when "write_length" is essentially just equal to "3 + payload + padding"
Code:
+               unsigned int write_length = 1 /* heartbeat type */ +
+                                           2 /* heartbeat length */ +
+                                           payload + padding;

Looks to me like it's only some cleanup, as "3 + payload + padding" or "1 + 2 + payload + padding" is used multiple times in the function.
 

oxrock

Gravity is a myth, the Earth SUCKS!
Our assignment was to manipulate bitmap image data.

We had to do various things like hide an image within another image, merge images and hide files within images by manipulating the bits of each pixel.

Took me a while to understand bit shifting but I finally did it.
I hate bit everything with a passion, thank sweet baby jesus that I never have to deal with it.

WBEV05T.gif


In other news, the passed couple days I've been working on a new game and being this is one of the few threads I actually keep up with, I figured I'd share. It's currently called "Deadly Dungeoneers" and is planned to be a topdown online coop dungeon crawling game although the current art does not represent that properly. I hate putting the artwork in because I'm far more interested in the coding. Only the title screen is functional so far but it's animated and stuff! I'm newer to game design and coding but I'm proud so far ( - my crappy art), so take a gander. Deadly Dungeoneers
 

Granadier

Is currently on Stage 1: Denial regarding the service game future
In other news, the passed couple days I've been working on a new game and being this is one of the few threads I actually keep up with, I figured I'd share. It's currently called "Deadly Dungeoneers" and is planned to be a topdown online coop dungeon crawling game although the current art does not represent that properly. I hate putting the artwork in because I'm far more interested in the coding. Only the title screen is functional so far but it's animated and stuff! I'm newer to game design and coding but I'm proud so far ( - my crappy art), so take a gander. Deadly Dungeoneers

Very cool. You always seem so passionate about your programming and the games you work on. It's really neat to see.

You are working in Python and Pygame right?
 

oxrock

Gravity is a myth, the Earth SUCKS!
Very cool. You always seem so passionate about your programming and the games you work on. It's really neat to see.

You are working in Python and Pygame right?
Correct. I've done some work with c# and the unity engine but I'm just SOOO much more comfortable with python for now. I know I should branch out but I love my native language!
 

Granadier

Is currently on Stage 1: Denial regarding the service game future
Correct. I've done some work with c# and the unity engine but I'm just SOOO much more comfortable with python for now. I know I should branch out but I love my native language!

Very cool. I've been looking at Python + Pygame for a while now, and I think I will make it my goal for the summer to get familiar with them both.

Looking forward to more updates about your games as you develop.
 

oxrock

Gravity is a myth, the Earth SUCKS!
Very cool. I've been looking at Python + Pygame for a while now, and I think I will make it my goal for the summer to get familiar with them both.

Looking forward to more updates about your games as you develop.
oh I'll be updating alright. It helps keep me motivated i think :)

As for your python/pygame goals, that's great! Finally something in this thread I actually have experience with, rofl. My brain will be free for picking should the need arise.
 

Granadier

Is currently on Stage 1: Denial regarding the service game future
oh I'll be updating alright. It helps keep me motivated i think :)

As for your python/pygame goals, that's great! Finally something in this thread I actually have experience with, rofl. My brain will be free for picking should the need arise.

Thanks, I appreciate it.
 

Zeus7

Member
Hi guys, I am a beginner to C++ and to programming. I have been asked to write a program which records & rates mobile apps. This is an exercise for my studies but I have no idea where to start. The program should display all app records, add/delete them also and produce totals for the number of apps, the total cost and the average cost.

Any help would be appreciated. Even a basic template of the functions so I have a basic structure of the program. Thanks
 

Nesotenso

Member
anyone here experienced with socket programming and network programming in Python?

How hard is to create an FTP client from scratch?

I know there is a module called ftplib in python but using that would make my semester project to easy.
 

tuffy

Member
anyone here experienced with socket programming and network programming in Python?

How hard is to create an FTP client from scratch?
Not hard at all. The FTP RFC is relatively short and easy to understand since the protocol is very basic. Features like the command channel can even be tested by pointing telnet at an FTP port and sending a few commands since they share a similar interface.
 

Nesotenso

Member
Not hard at all. The FTP RFC is relatively short and easy to understand since the protocol is very basic. Features like the command channel can even be tested by pointing telnet at an FTP port and sending a few commands since they share a similar interface.

i am new to network programming with python and working with sockets. The TA in my class demoed an echo client server model in class. I was going to make something similar at least on the client side using python. I was reading a chapter in the book Fundamentals of Network Programming with python and the chapter on ftp has the use of the ftplib module. Seems that would make my project too trivial.
 

tokkun

Member
This professor I am teaching a class with wants to tell freshmen programming students that it is always better to make a loop of the form:

Code:
for (unsigned int i = num_times; i > 0; --i) {...}

than

Code:
for (int i = num_times; i > 0; --i) {...}

based on the idea that it doesn't make sense to do something a negative number of times, that num_times should just be set to 0 if you don't want any iterations, and that you will still end up doing the right number of iterations even if num_times overflows.

I was trying to make the argument that the loop bounds could be a computed value, and thus might be negative, that neither approach is inherently better, that it depends on what assumptions you make about the bounds, and that the programmer must document whatever assumption they are using.

(The actual argument was over assembly programming, so there is no typechecking; the C-style representation is just there to illustrate the proposed functionality in a more readable way).
 

kingslunk

Member
This professor I am teaching a class with wants to tell freshmen programming students that it is always better to make a loop of the form:

Code:
for (unsigned int i = num_times; i > 0; --i) {...}

than

Code:
for (int i = num_times; i > 0; --i) {...}

based on the idea that it doesn't make sense to do something a negative number of times, that num_times should just be set to 0 if you don't want any iterations, and that you will still end up doing the right number of iterations even if num_times overflows.

I was trying to make the argument that the loop bounds could be a computed value, and thus might be negative, that neither approach is inherently better, that it depends on what assumptions you make about the bounds, and that the programmer must document whatever assumption they are using.

(The actual argument was over assembly programming, so there is no typechecking; the C-style representation is just there to illustrate the proposed functionality in a more readable way).

He's saying its better in the case which makes sure your iterator is not greater than zero. I think it's important to note that there's a check for i > zero. If that's the case then there is no reason to not used unsigned int.
 

Water

Member
This professor I am teaching a class with wants to tell freshmen programming students that it is always better to make a loop of the form:

Code:
for (unsigned int i = num_times; i > 0; --i) {...}

than

Code:
for (int i = num_times; i > 0; --i) {...}

based on the idea that it doesn't make sense to do something a negative number of times, that num_times should just be set to 0 if you don't want any iterations, and that you will still end up doing the right number of iterations even if num_times overflows.
The "unsigned" version creates a real concern of accidental underflow when someone chooses to decrement the loop counter inside the loop in some special case; the "int" version works correctly when that happens, while the "unsigned" version blows up.

The "even if num_times overflows" argument sucks. It's extremely rare that a loop would be intended to run not infinitely, but a number of times close to the largest int. (I don't think I've ever written such a loop in non-toy code!) But if one does come across a case like that, one should consider the bounds and correctness of the indexing very carefully instead of just relying on the practice of always using unsigned and (implicitly) hoping that the full range of unsigned is going to be enough even though positive signed ints would not have been.

If anything, I'd suggest people default to the "int" version of this loop.
 

oxrock

Gravity is a myth, the Earth SUCKS!
anyone here experienced with socket programming and network programming in Python?

How hard is to create an FTP client from scratch?

I know there is a module called ftplib in python but using that would make my semester project to easy.

I will have to conquer python network programming shortly myself. I wish us both the best of luck
 

squidyj

Member
I've had more WTFs writing this project than the rest of my time at uni combined.

Apparently my problem was I needed to flip the handedness calculation for my bitangent vector, against all logic and sense. It works beautifully but i have no idea why doing the opposite of the thing I should be doing would make this damn thing work.
 
Hi guys, I am a beginner to C++ and to programming. I have been asked to write a program which records & rates mobile apps. This is an exercise for my studies but I have no idea where to start. The program should display all app records, add/delete them also and produce totals for the number of apps, the total cost and the average cost.

Any help would be appreciated. Even a basic template of the functions so I have a basic structure of the program. Thanks

That's not enough to go on really. What's your input and data? How are you going to store that input while you're computing whatever? If you break down the problem description you can see what kind of classes/functions you'll need.
 

tokkun

Member
He's saying its better in the case which makes sure your iterator is not greater than zero. I think it's important to note that there's a check for i > zero. If that's the case then there is no reason to not used unsigned int.

The problem is that if 'num_times' is negative, the two loops behave in different ways. If you treat it as a signed value, the number of iterations is 0. If you treat it as unsigned, the number is 2^32 + num_times + 1 (for a 32-bit number), because this is what you will get when you cast a negative number to unsigned.

And it is impossible to know whether num_times was intended to be treated as signed or unsigned without either having comments saying "treat this as unsigned" or by tracing back to see how it was computed.
 

Rapstah

Member
Is there any reason to assume that the effects of a loop looping 0 times instead of 129 times are less destructive than a loop looping 255 times instead of -1 (0) times? You kind of never want either to happen.
 

tokkun

Member
Is there any reason to assume that the effects of a loop looping 0 times instead of 129 times are less destructive than a loop looping 255 times instead of -1 (0) times?

It is impossible to know without more information about the intent of the code. That is the argument I was trying to make.

You kind of never want either to happen.

Well, that is not necessarily true. It depends on the intent of the programmer.

Consider this example, where you want to capitalize all characters in a string that appear before the first '!'.

Code:
string str;
...
for (int pos = 0; pos < str.find('!'); ++pos) {
  str[pos] = to_upper(str[pos]);
}

In this case, the loop bound is negative, because string::find returns -1 if a character is not found. Having the loop do zero iterations is correct behavior. If the return value of str::find were treated as unsigned, you would get an array out of bounds error.

Conversely:

Code:
// Always returns a positive value.
int doSomething() { ...}

...

int a = doSomething();
int b = doSomething();

for (unsigned int i = 0; i < (unsigned int)(a + b); ++i)  {...}

In this case, assuming we know a and b are intended to be positive, then it is appropriate for us to treat their sum as unsigned, because it is possible that their sum could overflow and result in a negative number (which is not intended), but if that number is treated as unsigned, the loop will still do the correct number of iterations. If the sum were treated as signed, you would get zero iterations. (In real C++ it would be better to just use the long long datatype here, but you get the point).

The key in these examples is that it is impossible to have one single rule of thumb. The valid range must be documented. I know the first one works, because string::find documents that the value it returns can be negative. I know the second one works, because doSomething documents that its return values are strictly positive.
 

Water

Member
The problem is that if 'num_times' is negative, the two loops behave in different ways. If you treat it as a signed value, the number of iterations is 0. If you treat it as unsigned, the number is 2^32 + num_times + 1 (for a 32-bit number), because this is what you will get when you cast a negative number to unsigned.

And it is impossible to know whether num_times was intended to be treated as signed or unsigned without either having comments saying "treat this as unsigned" or by tracing back to see how it was computed.
Re: my earlier comments, have I misunderstood something? Because it kinda feels the professor's argument distills down to "let's use this defensive coding technique in case our assumptions are bad", yet his prescription is much more likely to cause trouble, and also do more damage when it does cause trouble.
 

tokkun

Member
Re: my earlier comments, have I misunderstood something? Because it kinda feels the professor's argument distills down to "let's use this defensive coding technique in case our assumptions are bad", yet his prescription is much more likely to cause trouble, and also do more damage when it does cause trouble.

Just to reiterate, the C++ code was merely provided to make the discussion more accessible.

The actual argument was about assembly for an ISA with a 16-bit word size (Don't get me started on the wisdom of teaching ASM to freshmen as their first language...). So there is no typing to document whether something should be considered signed or unsigned, and overflow occurs at 32,768 - a low enough bound that it is not unreasonable to assume that it could occur in some realistic code.

If you want to argue that treating them as unsigned is bad in some situations, you are preaching to the choir.

However, I don't agree that treating them as signed is inherently better either. It's just a question of assumptions. If you can safely assume that the value will be strictly positive, then unsigned makes sense. If you can safely assume that the value will be < 32,768, then signed makes sense. In the absence of any information to make those assumptions, neither is inherently better, so it is a bad idea to teach students that one is. Just tell them to make an assumption and document it in the code. i.e. "This subroutine assumes N is unsigned".

Incidentally I see most C++ style guides (and some linters) teach that treating bounds as signed is inherently better for many of the reasons you stated. This is based on an implicit assumption that overflow is rarer than having a negative iterator value. Not necessarily a bad assumption in practical use, but I wish they would state it explicitly.
 

Water

Member
The actual argument was about assembly for an ISA with a 16-bit word size (Don't get me started on the wisdom of teaching ASM to freshmen as their first language...). So there is no typing to document whether something should be considered signed or unsigned, and overflow occurs at 32,768 - a low enough bound that it is not unreasonable to assume that it could occur in some realistic code.
Okay, that changes a lot. I was assuming 32+ bits.

However, I don't agree that treating them as signed is inherently better either. It's just a question of assumptions. If you can safely assume that the value will be strictly positive, then unsigned makes sense. If you can safely assume that the value will be < 32,768, then signed makes sense. In the absence of any information to make those assumptions, neither is inherently better, so it is a bad idea to teach students that one is. Just tell them to make an assumption and document it in the code. i.e. "This subroutine assumes N is unsigned".
I was commenting on which should be the default until a reason is identified to do otherwise. When such a default is possible to identify, it gives structure to the information and aids learning; it has nothing to do with "inherently better".

BTW, is a index-decreasing loop preferred over index-increasing loops when writing this assembler? Just asking because I very rarely write decreasing loops in C++, and with increasing loops unsigned tends to be the right default.
Incidentally I see most C++ style guides (and some linters) teach that treating bounds as signed is inherently better for many of the reasons you stated. This is based on an implicit assumption that overflow is rarer than having a negative iterator value. Not necessarily a bad assumption in practical use, but I wish they would state it explicitly.
Sure, being explicit is good, but not at every single loop - that's exactly the reason we want to establish a sensible, robust default that handles the majority of cases.
 

tokkun

Member
BTW, is a index-decreasing loop preferred over index-increasing loops when writing this assembler? Just asking because I very rarely write decreasing loops in C++, and with increasing loops unsigned tends to be the right default.

It's easier to write index-decreasing in this ISA. It provides control flags for whether the last value written to the register file was positive, negative, or zero.

So an index-decreasing loop only needs

Code:
LOOP: [do something]
      Decrement Loop Index
      Branch if P-Flag to LOOP

Whereas increasing would require incrementing the index, then subtracting the index from the bounds and branching based on the result of that subtraction.

The specific argument we were having was related to the branch instruction:
Should it branch only on the positive flag (a.k.a. treat index as signed), or should it branch on both the positive and negative flags (a.k.a. treat index as unsigned).
 

alejob

Member
Are there any web developer/C# programming geniuses in here. I need a little help with webpages that is supposed to be customizable. I want to delete a few columns from a table, I cannot see the code that creates the table but I'm supposed to be able to modify it code in a .ascx file.

Is there a forum I can go and ask a question like this? The only help I have is this. I tried it and it doesn't work:

Hiding Single Columns

Sometimes you want to hide only one column in a grid that is dynamically created in the code. Since you can't get to the code without modifying the entire portlet, you can sometimes embed code in the .ascx file to hide it anyway. In this example, there is a GroupedGrid control on the page named "dgAwards" and the third column is unwanted. Since columns are numbered using a zero-based index, the third column has an index of 2.

Insert the following code:

Code:
 <% try {dgAwards.Columns[2].Visible = false;}catch{} %>




The .ascx file contains this where I believe the table is created some how.

Code:
<asp:TableRow Width="100%">
				<asp:TableCell Width="100%">
					<DIV runat="server" Visible="False" ID="divTermData" style="BORDER-RIGHT: 0px; BORDER-TOP: 0px; DISPLAY: block; MARGIN: 0px; POSITION:Relative; BORDER-LEFT: 0px; WIDTH: 99%; BORDER-BOTTOM: 0px; align: left"
						align="left" width="100%">
						<asp:Table cssclass="GroupedGrid" runat="server" ID="tblTermData" align="left"
							Width="100%"></asp:Table>
					</DIV>
				</asp:TableCell>
			</asp:TableRow>
 
Top Bottom