Banfa 597 Posting Pro Featured Poster

Youve missed to top of your code

  1. The easiest way to put a repeat into a game once it is already working is to move the whole game into a function, then add your loop that askes the user if they want to repeat in main and call the function. A do ... while loop works well for this since you always want to play the first game.

  2. I'm slightly surprised that the loop at line 31 doesn't just do into an infinite loop when you guess a letter that is in the word. Line 34 - 36 actually replace a single correctly guessed letter in the word and are only done once for each letter guessed.

You code could use a proper refactor it is messy and confusing. I can tell this because the lines

    //Prompt the user to guess a character in the word.
    cout << "(Guess) Enter a letter in word " << word << " > ";
    cin >> letter;

Appear 3 times in your code. This should not be required, this program can easil be written with the guess request in only 1 place (I would say just inside the do ... while loop. The only other loop required would be to look for multiple occurances of the same letter that was guessed.

Banfa 597 Posting Pro Featured Poster

Remember that strtok (which frankly I would avoid using if possible) works by overwriting the delimiters with '\0', it is not deleting anything. It returns pointers into the original string.

So when you call

char *token;
token = strtok("greetings pe()ple", "()");

it scans forward until it finds the '(', replaces it with '\0' and returns a pointer to the 'g' giving a string of "greetings pe". If you then call strtok again it

token = strtok(NULL, "()");

It scans past the ')' to the end of the string, finding no more delimiters it returns a pointer to "ple". At the end of this your original string now contains

"greetings pe\0)ple"

Nothing has been deleted but the '(' has been overwritten.

Banfa 597 Posting Pro Featured Poster

Line 171 is redundent, it repeats line 168.

The problem is line 169

  temp->previous = new_node->previous;

You are inserting the new node after temp so temp->previous should not change. new_node is ... well new, and so its previous pointer is set to NULL, you overwrite a value that does not need to be changed with NULL.

You actually need to alter the previous pointer of the now after temp in the orignal list to point at new_node.

Line 37 is strange, you set data to NULL but data is not a pointer it is an anmial and you can't assign NULL to it.

You have no polymorphism because of how you have declared your list

list<animal> * list1 = new list<animal>();

Instead of a list of base class pointers animal* which could point to all sorts of polymorphic animal derivertives you are actually storing an actua animal class that means anything you put in the list will be truncated to an animal rather than maintaining its full class.

You would be able to see what I meant if you fixed you list and output the contents.

Banfa 597 Posting Pro Featured Poster

That is your choice but it seems fairly general, I would just make it a whole separate class.

Banfa 597 Posting Pro Featured Poster

You probably forgot the definition of Person, or forgot to include the Person.h header file.

Banfa 597 Posting Pro Featured Poster

I think that rather begs the question why would you want to create a package that either doesn't have a sender or doesn't have a receiver? Almost by definition a package should have both.

Building on what @rubberman provided you can easily do this just by using the default constructor of package and then only setting the sender or receiver, you don't have to try and do everything with a constructor.

On a side note I thing a good addition to @rubberman Person class would be a method to indicate if the person was valid. Since you can clearly default construct a package without any people you would probably want to know that both the sender and receiver where valid before trying to dispatch the package. You will have to decide what criteria defines a valid Person, just name filled in or just name and zip or everything for example.

You need to create a copy constructor and assignment operator (they should always be created together) if you envisage a situation in the code where you will need to construct a new Package (or Person) from an existing one. However the code as written has the advantage that since it contains no allocated data it does not require an explicit deep copy (a constructor/assignment that allocates new memory) and therefore the default copy constructor and assignment operator provided by the compiler should work fine.

However you might still want to explicitly do it, our company coding standard states that you …

Banfa 597 Posting Pro Featured Poster

At line 19 and 20 you are using the symbols sys_nerr and sys_errlist but this is the first time the compiler has seen them, you have not previously declared them anywhere hence they are "undeclared".

You may have missed out a header file in which they are declared or you may have failed to write their declarations.

Banfa 597 Posting Pro Featured Poster

Your condition at line 45 if(exp >= 10) is wrong. Remeber that any number raise to the power of 0 is 1 but this is not what is embodied by your condition.

I would also say you are missing a newline or 2 at line 43.

Also storing exp as a long double in the function place could lead to error because all floating point types are only approximations so 10.0 minus 1.0 10 times may not equal exactly 0.0; however since you originally request the exponent as an integer, line 37, you can safely hold it as an integer for the whole calculation avoiding the floating point issue altogether.

Banfa 597 Posting Pro Featured Poster

Everything works fine if I use #include "Error_Handler.h" in the code.

But

#include "ErrorHandler.h"

Typo in post or actual mistake?

That said it would still help to see a few lines of code round the line producing the error. Also is this the first compiler error you get, if not what is the first one, remember it is always possible that subsequent compiler errors after the first one are just an artifact of the first error reported.

Banfa 597 Posting Pro Featured Poster

Your code seems to work fine for me when I compiled it with MinGW after I commented out #include "stdAfx.h".

Note that "Visual Basic C++ 6.0" is not a thing did you mean Visual C++ 6 which is rather old?

Banfa 597 Posting Pro Featured Poster

Line 54

template<class T >
T  display_array(T ItemType[10] , T const int arraySize)

This is invalid. Remeber that the compiler will substitude the type T in the template into the code provided in order to instatiate the function for you. You can do this by hand and should get the valid code. In this code if T is int (as is the case in main) then the code becomes

int  display_array(int ItemType[10] , int const int arraySize)

Hopefully it is obvious that the type of the 2nd parameter int const int is not valid. It should presumably be const int which would be removing the T from the beginning of the parameter type.

Line 59

cout << array1 << ' ' << arraySize;

array1 is not visible here, it is a local variable to main. Even if you changed it to ItemType, which is a valid local variable, you are just going to get an address (because ItemType is a pointer) or alternitively a compiler warning/error.

Line 66

 template<class T>


 streuct Item Type{
     int length;
     int array1[arraySize];
 }

You appear to be trying to declare struct ItemType, ignoring spelling an spaces you appear to be confusing type names and variable names. In various places in this code you use ItemType as a type name (here and top of main) or a variable name template at line 54. Also you have declared this structure as a template dependent on type T and …

Banfa 597 Posting Pro Featured Poster

Your problem is between lines 23 - 31. You get 3 numbers from the user but you only use 1 variable so everytime you overwrite the previous number that the user input. Then at line 31 you push a single value, the last onbe entered, onto the stack. This comment // PUSH NUMBERS ON STACK at line 30 is distinctly confusing because it is not what the code is doing at all.

You need to push the value onto the stack after each time the user enters it.

Banfa 597 Posting Pro Featured Poster

Problem 1: is at lines 45 and 48. You are passing pointers to objects that are on the stack but your class assumes that the objects are on the heap and treats the pointer accordingly. Calling delete on a pointer to a stack object is always going to fail.

In fact you could make your class safer by not passing a pointer in the constructor at all, if it needs to use a pointer internally that is fine, pass an int by value and have the constructor allocate the memory for it internally, that is keep all the memory management hidden inside the class. If in reality the code is using something a little more complex that an int then pass a const reference, leave the calling code resonsible for its memory and you class responsible for its internal memory. If the design requires that the pointer is passed in then use a smart pointer and let the pointer handle the memory deallocation.

Problem 2: You have no copy constructor. The posted code makes no use of it so it has shown up as a problem, however best practice is if you need an assignment operator then you need a copy constructor and vice versa as generally they do very similar operations.

Banfa 597 Posting Pro Featured Poster

Works fine for me using mingw 4.5.2 which is a c99 compiler. The only thing I would say is that the third line of StrCpy

    int size_destination = StrLen( destination ); //     !!!! Every time zero

is dangerous because you have no guarantee at all that the destination pointer currently points to a valid string which means you could end up scanning all of physical memory until you find a '\0' or cause a program crash. Strictly it is undefined behaviour because you may end up accessing an object outside its bounds.

Banfa 597 Posting Pro Featured Poster

When you type in that letter at line 9 cin enters an error state because it can not complete the requested operation, input a number. Additionally the letter you typed is left in the input buffer.

This means that at line 25 cin is still in an error state because you have not cleared it so it automatically fails. If you did clear the error it would still not enter the loop because the letter is still in the input buffer and it would immediately fail again at the operation read a number and put cin back into an error state.

Just inputing a letter when your program is expecting a number is not a good way to indicate the end of data you need a better strategy for reading data from the using for example

  • Sentinal Value: the list is finished when the user inputs a specific sentinal value, 0 or -1 are common ones. Any other value gets put in the list
  • After each value has been input ask if there is another value
  • Before asking for any values ask the user how many values they wish to input
  • Read the input as text, if it is a string of digits convert to a number otherwise end the loop

There are probably other strategies those are just what I can think of off the top of my head.

Banfa 597 Posting Pro Featured Poster

What was i initialised to before the loop started? This should work

i=a.begin();
while(i!=a.end())
{
  cout<<*i;
  i++;
}
Banfa 597 Posting Pro Featured Poster

My best guess would be that 22.5 has an exact represenation as a double (and may be a float) and 22.7 doesn't. However that is not the point, you don't need to know why one works and the other doesn't you need to know that using == is a mistake.

Banfa 597 Posting Pro Featured Poster

This is because floating point types (float, double, long double) only hold an approximation to the value you think they hold because of the way the value is encoded into the available memory (normally 4 or 8 bytes). e.g. You assigned 22.7 to d but actually it holds that as 22.7000000000001 in memory.

This approximation self evidently true particularly for a float because it (normally) has the same amount of memory as a long but holds a vastly larger range of numbers. Also floating point constants by definition have type double so 22.7 has type double, to use a float constant you have to post fix an F 22.7F has type float.

So in your code you take a double constant (which is an approximation of 22.7), convert it to a float in the assignment to f and then promote it back to a double for the comparison to d which itself is an approximation of 22.7.

During all that approximation, converting and promoting it is not surprising that the 2 values end up not exactly the same. In fact what is more surprising is that in your first example they don't end up different.

The rule of thumb usually used in comparing floating point types is that == always returns false and != always returns true. Your first code example shows that is not absolutely always the case but it is pretty much always the case in any but the most trivial examples.

Given that you should never use …

Banfa 597 Posting Pro Featured Poster

This is slightly stretching my, now 10 year out of date, recolection of WIN API programming but ...

I do not think GetStdHandle is likely to do what you want (with the caveat that of course I have no idea what you want so maybe it does) since it returns the standard handle for the current process but you want to set the stand output handle of your created process.

I seem to remember doing this by creating a pipe (CreatePipe) before creating the process and setting this as the std out handle in the STARTUPINFO structure passed to the process. Then you can read (and parse) the started applications output from the pipe.

Banfa 597 Posting Pro Featured Poster

If you want to run a command in a command prompt you need to use the /c or /k switches before the command line, i.e. "C:\Windows\System32\cmd.exe /c ping google.co.uk"

Try cmd /? at a command prompt

Banfa 597 Posting Pro Featured Poster

It is not cast to a float type because it is not a float type, since the type of p is char* the type of *p is char. This is an integer type and in the absence of a prototype indicating what type the parameter should be (which printf doesn't give because it accepts parameters of any type) this is then promoted using C rules about automatic promotion which basically means it gets promoted to an int.

Remember that the compiler does not store the type of the thing used originally to get the address stored in p so although you know that p points to a memory location that contains a float the compiler does not.

Banfa 597 Posting Pro Featured Poster

There are a couple of negative implications.

Firstly if you compile and run a program on 1 machine that writes a structure directly to a file in binary form using something like fwrite and reads it using fread and then you try and compile and run the same programme on a different machine and use the file created on the first machine the second machine may not read it correctly because the different machines may have inserted different padding in different places and may, ultimately have different sizes for the structure.

The second issue is one of memory wastage. Obviously any padding in your structure is not used for anything, it is unused and unusable (unless you are doing something very very suspect with pointers). How you write your structure, the order in which you place the members can effect the amount of padding in the structure, OK only by a few bytes (probably) but if you then have an array of those structures that wastage is multiplied. Now this wastage may be meanless on todays multi-gigabyte memory machines but it can easily be significant on microprocessors with much smaller memory. I have had to deal with this very problem when an array of poorly written structures was using more memory than needed on a platform that was running low on memory. My re-ordering the members of the structure (and replacing a few ints being used as booleans with a bit mapped int) I was able to save 20 bytes …

ddanbe commented: Great! +15
Ancient Dragon commented: good post :) +14
Banfa 597 Posting Pro Featured Poster

The (char *) is the cast command it tells the compiler what cawst you wish to make, in this case float* to char*. Note that casts of this type are not necessarily safe although I have seen such casts reasonbly often.

The at line 7 you tell printf you are passing it a parameter with type double with %f but what you actually pass is a variable of type char which is then automatically converted to int. This int has the value of the first byte in the memory that was being used to store the float. There is also a chance, depending on your Platform/OS, that the int is only 4 bytes long where as printf will be expecting a double of 8 bytes long so printf may well be reading more data off the stack than you put onto it which would be undefined behaviour.

The type specified by your printf format string (%f) must match the type actually passed to printf following the format string, many modern compilers parse the format string and emit warnings if they do not. For example mingw emits this message for line 7

test.c:7:5: warning: format '%f' expects type 'double', but argument 2 has type 'int'

Looking at memory

c contains the following 4 bytes (in hex on my system)
69 00 20 41

&c == p == 0x0028FF08 (When I ran it on my system this could be anything really)

Since p is a char* then *p is the first …

Banfa 597 Posting Pro Featured Poster

Personally I would ignore "(a Big-Oh answer will do)" and give an exact answer. You have the formula for fine after n days

fine = 2^(2^(n-1))

The second question is how many days will it take to for the fine to reach D (i.e. when fine = D) all you have to do is re-arrange your equation to find n in terms of fine (logarithms will help here)

ln(fine) = (2^n-1)ln(2)
ln(fine) / ln(2) = 2^(n-1)
ln(ln(fine) / ln(2)) = (n-1)ln(2)

Giving

n = (ln(ln(fine) / ln(2)) / ln(2)) + 1

This is simpler to read if written in terms of log to base 2

n = log2(log2(fine)) + 1

If you really want your big O notation look at your original formula and notice you are using an exponential of an exponential of days so O(e ^ e ^ x), remembering that Big O notation is an indication of how quickly something gets big.

Banfa 597 Posting Pro Featured Poster

An arry variable does not "point" at anything, it is an array with assigned memory and the properties of an array. On of the properties of an array is that when its symbol is used without an index it decays to a pointer to the first item in the array. Another property of arrays is that you can't pass arrays by value, that is you can not pass an array to any function, you can only pass a pointer to the first item in the array (what is most commonly done along with the size of the array) or a pointer to the array itself.

void fn1(char *p)
{
  printf("fn1: %d %d\n", sizeof(p), sizeof(*p));
}

void fn2(char p[])
{
  printf("fn2: %d %d\n", sizeof(p), sizeof(*p));
}

void fn3(char p[5])
{
  printf("fn3: %d %d\n", sizeof(p), sizeof(*p));
}

void fn4(char (*p)[5])
{
  printf("fn5: %d %d\n", sizeof(p), sizeof(*p));
}

In fn1, fn2 and fn3 p has type char* because it is just a char pointer and the values printed are 4(because I am using a 32 bit system) and 1. in fn4 p has type char (*)[5] and sizeof p is 4 still, but sizeof *p is now 5 because p points to an array.

The point is that in a function parameter using [] instead of * means nothing to the compiler although programmers sometimes use the [] notation to indicate the function is expecting an array rather than a pointer to a single thing. Also note that there is no …

Banfa 597 Posting Pro Featured Poster

Does it work? It prints "Inside A!!!" but does it print a number on the next line? If not then your program silently crashed.

It can get into A::func and print the first line (which is what my windows implementation does before reporting a crash at the next line) because up to that point it has not had to dereference this. It is only at line 13 when trying to access _dmember that it deferences this which is NULL and crashes.

This is all undefined behaviour so in theory it could run and print out you age (don't ask me how it got your age, the behaviour is undefined remember, it can do anything, perhaps it dialed into some government agency hacked their computers and got a copy of your birth certificate). The import thing to remember here is always avoid undefined behaviour, it's bad and it doesn't necessarily show up in testing, only after it has been deployed for 2 months.

Banfa 597 Posting Pro Featured Poster

When using rundll32. Read the description of this function, if you pass extra parameters on the command line of rundll32 then it passes a pointer to the parameters to the function it is calling.

That means a function called with parameters through rundll32 must take a const char * as its parameter type. Your function takes and int so what is actually being printed in the message box is the value of the pointer to this parameter which is also why it is different every time.

In your own code look at where you call GetProcAddress you have the function name wrong so a NULL pointer is almost certainly being returned. Since you then use the pointer without first checking that it is valid you are getting getting a memory access violation (because you are not allowed to dereference the NULL pointer.

Banfa 597 Posting Pro Featured Poster

This

pNResults.push_back(planetName());

for (i2 = 0; i2 <= cols; i2++)
{
    switch(i2)
    {
    case 1:
        pNResults.at(i).pName = string((char*)sqlite3_column_text(statement,i2));
        break;

    default:
        break;
    }
}

can be written more efficiently as

planetName planet;

if (cols >= 1)
{
    planet.pName = (char*)sqlite3_column_text(statement,1);
}

pNResults.push_back(planet);

it seems to me that the most likely problem is sqlite3_column_text returning NULL and you could modify this to check that

planetName planet;

if (cols >= 1)
{
    const char *data = (char*)sqlite3_column_text(statement,1);

    if (data != NULL)
    {
        planet.pName = data;
    }
    else
    {
        // report error
    }
}

pNResults.push_back(planet);

You should never just assume pointers are good.

If you implemented proper constructors, copy constructors and assignment operators for planetName then there are various other things you can do to simplfy your code.

This

for (i = 0; i < getCount("Planet_Names", bErrors); i++)
{
    ...
}

is very inefficient, every loop iteration you are querying the database store the result of getCount in a variable.

Use the debugger, it will show you where the crash is and by traversing the call stack you should be able to work out where the NULL pointer is.

Banfa 597 Posting Pro Featured Poster

It probably is showing you all the spaces it is just that it is using a variable width font and so thoses spaces are not very wide.

Banfa 597 Posting Pro Featured Poster

Line 16, the parameter to Thread is not named.

Line 18, third parameter to _beginthreadex consists of '(__stdcall*) (void *)' which is not a valid anything, perhaps it was meant to be the unnamed function parameter?

Banfa 597 Posting Pro Featured Poster

Code seems to work fine for me except that if there is not a new line at the end of the last number in the list your first loop produces a count that is 1 too small.

Banfa 597 Posting Pro Featured Poster

If you had an extra blank line ((or even a few spaces at the end of the last line) at the end of you dtata file then the !eof end condition in the while loop wouldn't be triggered, however the the request for input in ReadMixedExp would fail.

In this case you would go round the loop again but would fail to read new values for op1 and op2, they stay unchanged and you get an extra line of output.

You should have ReadMixedExp return some sort of status to indicate if the function correctly and then if it fails reading either op1 or op2 end the loop.

P.S. I personally don't really like having to go off to another website I know nothing about to retrieve your source, please put it in the post in future.

Banfa 597 Posting Pro Featured Poster

On line 1 when reading "12.4find" the first time it reads the line it reads the 12.4 and converts it to a float(? or double you don't say) and stores it in f.

The next time round the loop the next thing to read is "find", you request that this be converted to a float (or double) which can't be done. At this point the input stream enters an error state and (inputfile >> f) returns false and the loop stops.

If you want to read a file and handle errors then you would be better off reading each line as a std::string and then reading the value out of the string if you can

Open File

while(get_line_from_file)
{
   put line in stringstream
   read float from stringstream
   if (successful)
   {
     total += float
     count += 1
   }
}
Banfa 597 Posting Pro Featured Poster

So firstly you need to have an idea of what you expect your program to output, you haven't told us so it is rather hard for us to guess.

Secondly if the program is not performing as expected you need to find where the bug is, you could try examining the code but frankly if you haven't already seen it then you are unlikely to spot it now and without having the input data and the expected output I have no clues to go on as to where to look in your code to find an error and I don't care to examine each line of this much code.

That leaves you will tracing through the code to find the problem, you have 2 options here

  1. Us a symbolic debugger, this is a special program, you compile your program in debug mode and run it in the debugger and this allows you to examine the code as it is running including the values of variables and stack trace and memory contents etc.
  2. A poor second is to add additional output (cout) statements to trace the execution path of the program and value of variables. Although a poor second in a small program or localised piece of code this can be plenty.

Things that stand out as errors

  • The implementation of reduce acts only on local unitialised data and does not change the state of the instance it is operating on.
  • in main op1 and op2 are never set
  • in …
Banfa 597 Posting Pro Featured Poster

The problem is everywhere you new Node<TYPE>. The Node<Type> constructor does not set m_NextElement and everywhere you new it you don't set it either so in your list the final element in the list always has an invalid m_NextElement. When calling the list destructor this causes your program to exhibit undefined behaviour (in this case crash probably).

I would add a constructor to Node<Type> that initialised m_NextElement to NULL.

Banfa 597 Posting Pro Featured Poster

I am slightly surprised that you have declared NumericArray as a template I would have expected something similar to

// This is the interface for the derived class
class NumericArray: public Array<double,int>{
...
}

That is the derived class is an implementation of the template for a given type, or even

typedef Array<double,int> NumericArray;

That asside remeber that a template is a pattern it is not actual code it is instructions to the compiler on how to create the code if required. This means that in general the (non-specialised) template must include implementations of all the methods it declares (accept pure virtual ones although I'm not entirely sure of the use case for a pure virtual funciton in a template).

None of the methods in your template Array have any implementations so you will almost always get this error when ever you try to call a method on the template.

When a template class is compiled for a specific type then the compiler creates all the methods that explicitly called or all methods if the template is explicitly instantiated. It compiles all these methods and attaches them to the object for the current file. It then does this with all the code files the template is used in so you get multiple compiled copies of the method. The reason that this doesn't cause a problem for the linker is that they are marked has having weak linkage, this marking means that the linker is able to …

Banfa 597 Posting Pro Featured Poster

It is easiest to understand what << and >> do when you consider a number as a binary value (which is where convertion between binary and decimal come into it). This is because these are bitwise operators (2 of several), that is when they operate they consider individual bits of the operand rather than the overall number.

Considering just << (shift left) the operation is to shift the bits of the left hand operand left by the value of the right hand operand.

Considering the operation 10 << 2 the easiest way to understand what is happening is to consider the decimal value 10 in it's binary form 00001010b (I'm using 8 bits in this illustrantion but there would normally be more).

What happens is that all the digits in the binary representation are shifted (or moved) 2 places in the number to the left

00001010b --> 00001010xxb

The bottom 2 places are filled with 0

00001010xxb --> 0000101000b

And since this is an 8 bit number the top 2 digits are discarded

0000101000b --> 00101000b

And that is the answer converted back to decimal 00101000b = 40

Shift right is similar by the bits are shifted the other way 10 >> 2

Shift each digit 2 places to the right in the number discarding digits that fall off the right hand end

00001010b --> xx000010b

Fill in 0's at the left

xx000010b --> 00000010b

That's you answer the result is 00000010b = 2

The majority of processors have an …

Banfa 597 Posting Pro Featured Poster

Line 8 initialising b to 0 means that at line 9 you get a divide by zero error while trying to get the remainder after dividing a by b.

Banfa 597 Posting Pro Featured Poster

That doesn't fix your problem it hides it. The problem is in your for loop at lines 23, 28, 29, 31 and 32 where you access pArray[s + 1] and names[s + 1]. Since the loop is written for(int s = 0; s < count; s++) in the final iteration s has the value count-1 therefore (s + 1) == count and that means you are accessing the arrays pArray and names outside there bounds which is what is causing your errors.

What you did hide the problem by moving the location in memory used to store pArray, since an out of bounds array access produces undefined behaviour just because the program started working doesn't mean you fixed the problem, just that it no longer showed up as an invalid address access.

When using <LoopCounter>+1 to access arrays you must always be careful that you adjust your loop end condition accordingly so that you do not end up with out of bound array accesses.

BTW you could make your sort more efficient, one of the features of bubble sort is that after each iteration the top (or in your case bottom) item is now correct and no longer needs checking, that means that for each interation of the outer loop of the sort the inner loop can be reduced by 1, your inner loop could be written as for(int s = 0; s < (count - (i + 1)); s++) which would improve the efficiency of the sort and fix …

Banfa 597 Posting Pro Featured Poster

I assume you mean at line 11, that is because operator>> on an istream into a string uses any white space as a separator, it is specifically coded to only read up to the space. If you want to get an entire line into a string use std::getline, declared in string.

Banfa 597 Posting Pro Featured Poster

This Val & 0xFF is an unecessary operator since you already know at this point that 0 < Val < 0xFF

Banfa 597 Posting Pro Featured Poster

@L7Sqr - Doh! you're right of course.

@L7Sqr & @tinstaafl - Both your solutions use C++ but this is the C forum and in fact the original solution is valid on in C (it uses an implied return type).

I am beginning to suspect the original solution may well be the best C solution.

Banfa 597 Posting Pro Featured Poster

I assume you are missing a 0 between the first ? :.

You could use the modulous (%) operator rather than a second test. Whether this is better rather depends on the processor it is running on though

Clip(int Val)
{
    return ((curr < 0) ? 0 : (curr %= 256));
}
Banfa 597 Posting Pro Featured Poster

At line 14 you still have a and b declared as int but you scanf them as floats at line 16 which will produce the strange results you are seeing.

jandanielsaclolo commented: Fixed the code but it doesn't fixed the problem, It gives me 0.00 +0
Banfa 597 Posting Pro Featured Poster

Not quite sure where sizeInTChars comes from but it would appear that it's value is 0 when is should be at least 1 or 2. This looks like parameter checking of a function so I'm guessing sizeInTChars might be a function parameter in which case somewhere you have called the function (xtoa?) with invalid parameters.

Banfa 597 Posting Pro Featured Poster

Precedence is not about which operator is evaluated first, it is about how the operands bind to the operators.

So in the expression A || (B && C) the parentheses overide precedence, B and C bind to && and A and the result of the && bind to the ||.

In the expression A || B && C there are no parentheses to overide precedence, so in this case precedence takes effect an since && has a higher precedence the B and C bind to the && and A and the result of the && bind to the ||. Note this is the same as the previous example.

In the expression (A || B) && C the parentheses actually overide precedence. Normally the && having a higher precedence would use B as it's left hand side however because of the parentheses the A and B bind to || and the result of the || and C bind to the &&.

Again this is not about which operator gets evaluated first, they are evaluated as they are needed. This is about what each operator uses as its operands.

Banfa 597 Posting Pro Featured Poster

Because since i Have mentioned the brace for && operator to make it execute first

The parentheses () do not make the contained code execute first. That is a simplistic way to think of them and wrong. The parentheses create a sub-expression with-in a complete expression. The sub-expression is evaluated when it's value is required.

So in the statement

j = j || (printf("you can")&&(i=5));

the expression is j || (printf("you can")&&(i=5)) which consists of 2 sub-expressions j and (printf("you can")&&(i=5)). The operator using these 2 sub-expressions is || which as deceptikon explained is a short-circuiting operator (only || and && are short circuit operators in C/C++) that means it evaluates its left hand expression first, since this is or if it is true the answer can be deduced from that single result and the right hand expression is not evaluated. j is 7 and this equates to true so in your code the left hand sub-expression j is evaluated as true and because of that the right hand sub-expression (printf("you can")&&(i=5)) is never evaluated.

In your more simple example a=4*(5+6) the parentheses create a sub-expression (5+6) but since the multiplication operator requires the values of both its sub-expression this is always evaulated. It is platform dependent weather the sub-expressions (5+6) or 4 is actually evaluated first but both are evaluated before the multiplication is done.

Banfa 597 Posting Pro Featured Poster

At line 107 you are missing the const on the declaration of the inclass parameter

Your declaration and definition of list_clear at lines 28 and 55 do not match

Banfa 597 Posting Pro Featured Poster

You have defined the TPhysics constructor at both line 32 and 52

Banfa 597 Posting Pro Featured Poster

Does database.txt use '\n' as end of line characters?
Does database.txt have a '\n' on the last line in the file?