#trying to come up with an algorithm for a foor loop

7 messages · Page 1 of 1 (latest)

twilit tapir
#

kind of hard to explain waht im doing but i wanna make a for loop like this

for (int i = 0; i < IDK; i ++) {
    
}

Now i want some variable say int bruh;

when bruh >= 8, then the for loop runs as if IDK = 8, however if bruh < 8, then the foor loop runs as if IDK = bruh, idk if that makes sense but eyah

sage muskBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.

grizzled chasm
#

oh wait, this is C, so I guess you can do

int limit = bruh < 8 ? bruh : 8;
// ...
i < limit
#

anyhow, it just means you're taking the lower of the two values and using that as the limit

twilit tapir
sage muskBOT
#
What Is the Conditional Operator?

The conditional operator, (colloquially called ternary operator) of the form Condition ? T : F evaluates T if the Condition is true, otherwise F.

The result of the whole expression is either the expression T or F. This also means that T and F must have compatible types.

Example

A classic use case for the conditional operator is the min function.

int min(int a, int b) {
    return a < b ? a : b;
}

This function chooses a if a is lower than b, or b otherwise.

Benefits over If-Statements
  • more concise code
  • makes it easier to be const-correct
Downsides
  • can be hard to read, especially when nested and formatted poorly