There are a few problems with your code.

First of all, argv[i+1] is an illegal operation if you're doing i < argc in the for. You need to change i < argc to i < argc - 1 in the for.

Secondly, you are probably not comparing the strings you want. argv[0] is the string representing the path of your program; the first argument passed to your program is argv[1]. Therefore, you need to change the i = 0 in the for to i = 1.

Finally, if you only want the biggest string, you should not do any printing in the for loop. Rather, you should create two variables like max_length and max_length_idx where you would store the length and index of the largest string found so far. Then, after the for loop, your program would print out the string argv[max_length_idx].

Answer from houbysoft on Stack Overflow
🌐
Cplusplus
cplusplus.com › reference › string › string › compare
std::string::compare
Compares the value of the string object (or a substring) to the sequence of characters specified by its arguments. The compared string is the value of the string object or -if the signature used has a pos and a len parameters- the substring that begins at its character in position pos and spans ...
🌐
CodinGame
codingame.com › playgrounds › 14213 › how-to-play-with-strings-in-c › string-length-string-comparison
How to play with strings in C
CodinGame is a challenge-based training platform for programmers where you can play with the hottest programming topics. Solve games, code AI bots, learn from your peers, have fun.
🌐
wikiHow
wikihow.tech › computers and electronics › software › programming › c programming languages › how to compare two strings in c programming: 10 steps
How to Compare Two Strings in C Programming: 10 Steps
June 16, 2025 - Now that you have the function in place, you can use an If...Else statement to display which string is longer. strncmp() will return 0 if the strings are the same length, a positive number if str1 is larger, and a negative number if str2 is larger.
🌐
Scaler
scaler.com › home › topics › string comparison in c
String Comparison in C - Scaler Topics
January 11, 2024 - We can use recursion to compare two strings, so we'll calculate the lengths of both strings and the compareTwoString function will keep calling itself until the condition becomes false.
🌐
Reddit
reddit.com › r/cprogramming › fast string comparisons in c
r/cprogramming on Reddit: Fast String comparisons in C
October 29, 2023 -

Hi, I'm working just for fun on a fast comparison for strings written in C, with the intent of being faster than the normal strncmp function, which is currently the code bellow

```
int fast_strncmp(const char *str1, const char *str2, int len) {
    const char *final_pos = (str1 + len) - 4;
    while (str1 < final_pos) {
        // if characters differ, or end of the second string is reached
        if (*((uint32_t *)str1) != *((uint32_t *)str2)) {
            break;
        }
        // move to the block of characters
        str1 += 4;
        str2 += 4;
    }
    final_pos += 4;
    while (str1 < final_pos) {
        if (*str1 != *str2 || *str1 == 0 || *str2 == 0) {
            return *str1 - *str2;
        }
        // move to the next pair of characters
        str1++;
        str2++;
    }
    return 0;
}
```

Is there any clear problem with the code that could make it a bad option for fast string comparisons. When I wrote it a couple of weeks ago, I didn't think there could be any problem with it, but this week I was watching a couple of videos about C programming and it was mentioned that casting an array of 4 uint8_t to a uint32_t could be a problem. I'm even using this function at work and haven't had a single problem or warning, but since I'm planning to make a youtube video about it, I want to guarantee that my code won't be a problem for other people.

On top of that I've made a couple of benchmarks on the performance to be sure it really is fast, so I've compared it to strncmp and an implementation by https://github.com/mgronhol, that I found here: https://mgronhol.github.io/fast-strcmp/, which got me the following results:

EDIT: reddit was not cooperating with me posting the results text in a well formatted way, so here's the link to the file:

https://github.com/BenjamimKrug/fast_string_comparison/blob/main/results.txt

As you can see, running on the STM32 and the ESP32, my algorithm runs faster by a little compared to the fast_compare function by mgronhol, but running on my PC, it's performing terribly. Does anyone know why that is?

You can find more info about the code in my github repository where I put everything related to this test: https://github.com/BenjamimKrug/fast_string_comparison

P.S.: Sorry if this is the wrong subreddit for this kind of thing, I was going to post it on r/programming, but after reading the rules, I saw that maybe it was best to post it here.

EDIT: fixed code formatting

Find elsewhere
🌐
GNU
gnu.org › software › libc › manual › html_node › String_002fArray-Comparison.html
String/Array Comparison (The GNU C Library)
If the lengths differ, the shorter non-digit sequence is extended with the input string character immediately following it (which may be the null terminator), the other sequence is truncated to be of the same (extended) length, and these two sequences are compared lexicographically.
🌐
Upgrad
upgrad.com › home › tutorials › software & tech › strcmp in c
strcmp in C | String Comparison Function with Examples
February 5, 2025 - Yes, you can use strcmp in C with example in sorting algorithms, such as Bubble Sort or Quick Sort, to compare and arrange strings in lexicographical order. strcmp() compares each character.
🌐
freeCodeCamp
freecodecamp.org › news › strcmp-in-c-how-to-compare-strings-in-c
strcmp in C – How to Compare Strings in C
April 27, 2023 - If the two strings are equal up to the end of the shorter string, strcmp() returns a negative, zero, or positive value depending on whether the longer string has a character with a smaller, equal, or greater ASCII value than the null character. Actually, the C compiler implements this logic of comparing the ASCII values of characters in two strings and returning the result accordingly.
🌐
Programiz
programiz.com › c-programming › library-function › string.h › strcmp
C strcmp() - C Standard Library
#include <stdio.h> #include <string.h> int main() { char str1[] = "abcd", str2[] = "abCd", str3[] = "abcd"; int result; // comparing strings str1 and str2 result = strcmp(str1, str2); printf("strcmp(str1, str2) = %d\n", result); // comparing strings str1 and str3 result = strcmp(str1, str3); printf("strcmp(str1, str3) = %d\n", result); return 0; }
🌐
Lua Ternary
nachtimwald.com › posts › constant time string comparison in c
Constant Time String Comparison in C | John's Blog
April 2, 2017 - The OR XOR combo has been reviewed ... projects so… Well, my focus is on how to implement it specifically with strings in C. Most of the C versions I’ve seen, assume bytes and take the comparison length as an argument....
🌐
Shiksha
shiksha.com › home › it & software › it & software articles › programming articles › compare strings with strcmp function in c
Compare Strings with strcmp() Function in C - Shiksha Online
December 21, 2023 - First, the length of the string is determined using strlen(). Then, the characters of the string are compared from the start and end until the middle of the string is reached. If all the characters match, the string is a palindrome.
🌐
Reddit
reddit.com › r/learnprogramming › fast string comparisons in c
r/learnprogramming on Reddit: Fast String comparisons in C
October 29, 2023 -

Hi, I'm working just for fun on a fast comparison for strings written in C, with the intent of being faster than the normal strncmp function, which is currently the code bellow

```
int fast_strncmp(const char *str1, const char *str2, int len) {
    const char *final_pos = (str1 + len) - 4;
    while (str1 < final_pos) {
        // if characters differ, or end of the second string is reached
        if (*((uint32_t *)str1) != *((uint32_t *)str2)) {
            break;
        }
        // move to the block of characters
        str1 += 4;
        str2 += 4;
    }
    final_pos += 4;
    while (str1 < final_pos) {
        if (*str1 != *str2 || *str1 == 0 || *str2 == 0) {
            return *str1 - *str2;
        }
        // move to the next pair of characters
        str1++;
        str2++;
    }
    return 0;
}
```

Is there any clear problem with the code that could make it a bad option for fast string comparisons. When I wrote it a couple of weeks ago, I didn't think there could be any problem with it, but this week I was watching a couple of videos about C programming and it was mentioned that casting an array of 4 uint8_t to a uint32_t could be a problem. I'm even using this function at work and haven't had a single problem or warning, but since I'm planning to make a youtube video about it, I want to guarantee that my code won't be a problem for other people.

On top of that I've made a couple of benchmarks on the performance to be sure it really is fast, so I've compared it to strncmp and an implementation by https://github.com/mgronhol, that I found here: https://mgronhol.github.io/fast-strcmp/, which got me the following results:

EDIT: reddit was not cooperating with me posting the results text in a well formatted way, so here's the link to the file:

https://github.com/BenjamimKrug/fast_string_comparison/blob/main/results.txt

As you can see, running on the STM32 and the ESP32, my algorithm runs faster by a little compared to the fast_compare function by mgronhol, but running on my PC, it's performing terribly. Does anyone know why that is?

You can find more info about the code in my github repository where I put everything related to this test: https://github.com/BenjamimKrug/fast_string_comparison

P.S.: Sorry if this is the wrong subreddit for this kind of thing, I was going to post it on r/programming, but after reading the rules, I saw that maybe it was best to post it here.

EDIT: fixed code formatting

Top answer
1 of 14
104

I don't think there is a way to do variable length string comparisons completely in preprocessor directives. You could perhaps do the following though:

#define USER_JACK 1
#define USER_QUEEN 2

#define USER USER_JACK 

#if USER == USER_JACK
#define USER_VS USER_QUEEN
#elif USER == USER_QUEEN
#define USER_VS USER_JACK
#endif

Or you could refactor the code a little and use C code instead.

2 of 14
17

[UPDATE: 2021.01.04]

One thing that has changed since I first posted this in 2014, is the format of #pragma message.

Nowadays, the parens are required!

#pragma message ("USER    IS " USER)
#pragma message ("USER_VS IS " USER_VS)

That said, the 2016 code (using characters, not strings) still works in VS2019.

But, as @Artyer points out, the version involving c_strcmp will NOT work in ANY modern compiler.

[UPDATE: 2018.05.03]

CAVEAT: Not all compilers implement the C++11 specification in the same way. The below code works in the compiler I tested on, while many commenters used a different compiler.

Quoting from Shafik Yaghmour's answer at: Computing length of a C string at compile time. Is this really a constexpr?

Constant expressions are not guaranteed to be evaluated at compile time, we only have a non-normative quote from draft C++ standard section 5.19 Constant expressions that says this though:

[...]>[ Note: Constant expressions can be evaluated during translation.—end note ]

That word can makes all the difference in the world.

So, YMMV on this (or any) answer involving constexpr, depending on the compiler writer's interpretation of the spec.

[UPDATED 2016.01.31]

As some didn't like my earlier answer because it avoided the whole compile time string compare aspect of the OP by accomplishing the goal with no need for string compares, here is a more detailed answer.

You can't! Not in C98 or C99. Not even in C11. No amount of MACRO manipulation will change this.

The definition of const-expression used in the #if does not allow strings.

It does allow characters, so if you limit yourself to characters you might use this:

#define JACK 'J'
#define QUEEN 'Q'

#define CHOICE JACK     // or QUEEN, your choice

#if 'J' == CHOICE
#define USER "jack"
#define USER_VS "queen"
#elif 'Q' == CHOICE
#define USER "queen"
#define USER_VS "jack"
#else
#define USER "anonymous1"
#define USER_VS "anonymous2"
#endif

#pragma message "USER    IS " USER
#pragma message "USER_VS IS " USER_VS

You can! In C++11. If you define a compile time helper function for the comparison.

[2021.01.04: CAVEAT: This does not work in any MODERN compiler. See comment by @Artyer.]

// compares two strings in compile time constant fashion
constexpr int c_strcmp( char const* lhs, char const* rhs )
{
    return (('\0' == lhs[0]) && ('\0' == rhs[0])) ? 0
        :  (lhs[0] != rhs[0]) ? (lhs[0] - rhs[0])
        : c_strcmp( lhs+1, rhs+1 );
}
// some compilers may require ((int)lhs[0] - (int)rhs[0])

#define JACK "jack"
#define QUEEN "queen"

#define USER JACK       // or QUEEN, your choice

#if 0 == c_strcmp( USER, JACK )
#define USER_VS QUEEN
#elif 0 == c_strcmp( USER, QUEEN )
#define USER_VS JACK
#else
#define USER_VS "unknown"
#endif

#pragma message "USER    IS " USER
#pragma message "USER_VS IS " USER_VS

So, ultimately, you will have to change the way you accomlish your goal of choosing final string values for USER and USER_VS.

You can't do compile time string compares in C99, but you can do compile time choosing of strings.

If you really must do compile time sting comparisons, then you need to change to C++11 or newer variants that allow that feature.

[ORIGINAL ANSWER FOLLOWS]

Try:

#define jack_VS queen
#define queen_VS jack

#define USER jack          // jack    or queen, your choice
#define USER_VS USER##_VS  // jack_VS or queen_VS

// stringify usage: S(USER) or S(USER_VS) when you need the string form.
#define S(U) S_(U)
#define S_(U) #U

UPDATE: ANSI token pasting is sometimes less than obvious. ;-D

Putting a single # before a macro causes it to be changed into a string of its value, instead of its bare value.

Putting a double ## between two tokens causes them to be concatenated into a single token.

So, the macro USER_VS has the expansion jack_VS or queen_VS, depending on how you set USER.

The stringify macro S(...) uses macro indirection so the value of the named macro gets converted into a string. instead of the name of the macro.

Thus USER##_VS becomes jack_VS (or queen_VS), depending on how you set USER.

Later, when the stringify macro is used as S(USER_VS) the value of USER_VS (jack_VS in this example) is passed to the indirection step S_(jack_VS) which converts its value (queen) into a string "queen".

If you set USER to queen then the final result is the string "jack".

For token concatenation, see: https://gcc.gnu.org/onlinedocs/cpp/Concatenation.html

For token string conversion, see: https://gcc.gnu.org/onlinedocs/cpp/Stringification.html#Stringification

[UPDATED 2015.02.15 to correct a typo.]

🌐
GeeksforGeeks
geeksforgeeks.org › c language › strcmp-in-c
strcmp() in C %%sep%% %%sitename%% - GeeksforGeeks
December 13, 2025 - The strcmp function in C is used to compare two strings, with syntax: int strcmp(const char *str1, const char *str2);, where str1 and str2 are the strings to compare.