Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

In C and C++, what methods can prevent accidental use of the assignment(=) where equivalence(==) is needed?

In C and C++, it is very easy to write the following code with a serious error.

The error is that the if statement should have been:

As coded, it will exit every time, because the assignment of the confirmExit variable occurs, then confirmExit is used as the result of the expression.

Are there good ways to prevent this kind of error?

  • coding-standards

Bill the Lizard's user avatar

  • 41 Yes. Turn on compiler warnings. Treat warnings as errors and it is not an issue. –  Martin York Aug 25, 2012 at 6:39
  • possible duplicate of Doesn't "if (0 == value) ..." do more harm than good? –  Martin York Aug 25, 2012 at 7:05
  • 10 In the given example, the solution is easy. You assign it a boolean value, thus use it as a boolean: if (confirmExit) . –  Secure Aug 25, 2012 at 7:16
  • 4 The problem is that the mistake was made by the C language "designers", when they chose to use = for the assignment operator and == for equality comparison. ALGOL used :=, because they specifically wanted to use = for equality comparison, and PASCAL and Ada followed the ALGOL decision. (It is worth noting that, when DoD solicited a C-based entry into the DoD1 bake-off, that eventually yielded Ada, Bell Labs declined, saying that "C was not now and would not ever be robust enough for DoD mission-critical software." One wishes that DoD and the contractors had listened to Bell Labs on this.) –  John R. Strohm Aug 25, 2012 at 12:57
  • 4 @John, the choice of symbols isn't the problem, it's the fact that assignments are also an expression that returns the assigned value, allowing either a = b or a == b inside a conditional. –  Karl Bielefeldt Aug 25, 2012 at 16:46

8 Answers 8

The best technique is to increase the warning level of your compiler. It will then warn you about potential assignment in the if conditional.

Make sure you compile your code with zero warnings (which you should be doing anyway). If you want to be pedantic then set your compiler to treat warnings as errors.

Using Yoda conditionals (putting the constant on the left hand side) was another technique that was popular about a decade ago. But they make the code harder to read (and thus maintain because of the unnatural way they read (unless you are Yoda)) and provide no greater benefit than increasing the warning level (which also has extra benefits of more warnings).

Warnings are really logical errors in the code and should be corrected.

Deduplicator's user avatar

  • 2 Definitely go with the warnings, not the Yoda conditionals - you can forget to do the conditional constant first as easily as you can forget to do ==. –  Michael Kohne Aug 25, 2012 at 12:00
  • 10 I got a pleasant surprise that the most voted answer for this question is 'turn compiler warnings into errors'. I was expecting the if (0 == ret) horror. –  James Aug 25, 2012 at 21:17
  • 2 @James: ... not to mention it will not work for a == b !! –  Emilio Garavaglia Aug 26, 2012 at 21:30
  • 7 @EmilioGaravaglia: There's an easy workaround for that: Just write 0==a && 0==b || 1==a && 1==b || 2==a && 2==b || ... (repeat for all possible values). Don't forget the obligatory ...|| 22==a && 22==b || 23==a && 24==b || 25==a && 25==b || ... error, or the maintenance programmers won't have any fun. –  user281377 Nov 6, 2012 at 12:16
  • In Visual Studio/Visual C++, add 4706 to the list of warnings to be treated as errors. Look for the option named "Treat Specific Warnings As Errors", it's on the 'Advanced' or 'All Options' section of 'C/C++'. I also suggest adding 4715 for missing return statements. –  Dwedit Sep 12, 2021 at 20:10

You could always do something radical like testing your software. I don't even mean automated unit tests, just the tests every single experienced developer does out of habit by running his new code twice, once confirming the exit and once not. That's the reason most programmers consider it a non-issue.

Karl Bielefeldt's user avatar

  • 1 Easy to do when the behaviour of your program is completely deterministic. –  James Aug 25, 2012 at 21:19
  • 4 This particular issue can be hard to test for. I've seen people bitten by rc=MethodThatRarelyFails(); if(rc = SUCCESS){ more than once, especially if the method fails only in conditions that are hard to test for. –  user53141 Aug 25, 2012 at 23:50
  • 4 @StevenBurnap: That's what mock objects are for. Proper testing includes testing of failure modes. –  Jan Hudec Nov 6, 2012 at 13:47
  • 1 This is the correct answer. –  Lightness Races in Orbit Jan 3, 2016 at 23:23

A traditional way to prevent the incorrect use of assignments within expression is to place the constant on the left and the variable on the right.

The compiler will report an error for the illegal assignment to a constant similar to the following.

The revised if condition would be:

As shown by comments below, this is considered by many to be an inappropriate method.

  • 9 Also known as Yoda conditionals: wiert.me/2010/05/25/… and stackoverflow.com/questions/8591182/… and programmers.stackexchange.com/questions/16908/… –  Martin York Aug 25, 2012 at 7:05
  • 16 It should be noted that doing things this way will make you fairly unpopular. –  riwalk Aug 25, 2012 at 18:03
  • 13 Please don't recommend this practice. –  James Aug 25, 2012 at 21:18
  • 5 It also doesn't work if you need to compare two variables to each other. –  dan04 Aug 27, 2012 at 2:36
  • Some languages actually allow assigning 1 to a new value (yes, I know the Q is a bout c/c++) –  Matsemann Nov 7, 2012 at 9:32

I agree with everyone saying "compiler warnings" but I want to add another technique: Code reviews. If you have a policy of reviewing all code that gets committed, preferably before it's committed, then it's likely this kind of thing will be caught during review.

Tyler's user avatar

  • 2 I disagree. Especially = instead of == can easily slip through by reviewing the code. –  Simon Jun 15, 2017 at 19:28
  • As if we don't review every single line of code already... –  fjch1997 Jan 20 at 1:25

First, raising your warning levels never hurts.

If you do not want your conditional to test the result of an assignment within the if statement itself, then having worked with a lot of C and C++ programmers over the years, and having never heard that comparing the constant first if(1 == val) was a bad thing, you could try that construct.

If your project leader approves of your doing this, don't worry about what other people think. The real proof is whether you or someone else can make sense of your code months and years from now.

If you intention was to test the result of an assignment, however, then using higher warnings might [probably would have] caught the assignment to a constant.

octopusgrabbus's user avatar

  • I raise a sceptical eyebrow at any non-beginner programmer who sees a Yoda conditional and doesn't immediately understand it. It's just a flip, not difficult to read, and certainly not as bad as some comments are claiming. –  underscore_d Jan 1, 2016 at 17:39
  • @underscore_d At most of my employers, assignments within a conditional were frowned on. The thinking was it was better to separate the assignment from the conditional. The reason for being clearer, even at the expense of another line of code was the sustaining engineering factor. I worked in places that had large code bases and a lot of maintenance backlogged. I fully understand someone might want to assign a value, and branch on the condition resulting from the assignment. I see it being done more often in Perl, and, if the intent is clear, I'll follow the design pattern of the author. –  octopusgrabbus Jan 2, 2016 at 18:54
  • I was thinking about Yoda conditionals alone (like your demo here), not with assignment (as in the OP). I don't mind the former but don't much like the latter either. The only form I deliberately use is if ( auto myPtr = dynamic_cast<some_ptr>(testPtr) ) { as it avoids keeping a useless nullptr in scope if the cast fails - which is presumably the reason C++ has this limited ability to assign within a conditional. For the rest, yeah, a definition should get its own line, I'd say - much easier to see at-a-glance and less prone to assorted slips-of-the-mind. –  underscore_d Jan 2, 2016 at 20:30
  • @underscore_d Edited answer based on your comments. Good point. –  octopusgrabbus Jan 2, 2016 at 22:24

Late to the party as ever, but Static Code Analysis is the key here

Most IDEs now provide SCA over and above the syntactic check of the compiler, and other tools are available, including those that implement the MISRA (*) and/or CERT-C guidelines.

Declaration: I am part of the MISRA C working group, but I'm posting in a personal capacity. I'm also independent of any tool vendor

Andrew's user avatar

Use const when possible. (Which you should do anyway.)

Solomon Ucko's user avatar

Just use left hand assignment, compiler warnings can help but you have to make sure you get the right level otherwise you'll either be swamped with pointless warnings or won't be told ones you want to see.

Inverted Llama's user avatar

  • 5 You'd be surprised at how few pointless warnings modern compilers generate. You might not think a warning is important, but in most cases you're just wrong. –  Kristof Provost Nov 7, 2012 at 12:54
  • Check out the book, "Writing Solid Code" amazon.com/Writing-Solid-Microsoft-Programming-Series/dp/… . It starts with a great discussion about compilers and how much benefit we could be getting from warning messages and even more extensive static analysis. –  DeveloperDon Nov 7, 2012 at 14:43
  • @KristofProvost I've managed to get visual studio to give me 10 copies of the exact same warning fro the same line of code, then when this issue was 'fixed' it resulted in 10 identical warnings about the same line of code saying that the original method was better. –  Inverted Llama Nov 8, 2012 at 11:09
  • @InvertedLlama That's beside the point. You still have to think about what you are doing to fix it, which includes not doing something else dangerous. –  Caleth Jun 1, 2020 at 14:57

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Software Engineering Stack Exchange. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged c++ coding-standards or ask your own question .

Hot network questions.

  • What is the difference between Hof and Bauernhof?
  • Why are ETFs so bad at tracking Japanese indices?
  • Smallest Harmonic number greater than N
  • Mismatching Euler characteristic of the Torus
  • Sum of square roots (as an algebraic number)
  • What scientific evidence there is that keeping cooked meat at room temperature is unsafe past two hours?
  • What are these cylinders with holes for in a universal PCB enclosure?
  • Why is array access not an infix operator?
  • Structure that holds the twin-engine on an aircraft
  • Word for a country declaring independence from an empire
  • What is the difference between Xを同伴する and Xを同伴させる?
  • Is it theoretically possible for the Sun to go dark?
  • Book where the populace is split between two sects, that of the “hand” and that of the “mind"
  • Parody of early D&D rules set, and specifically character creation, as part of a web novel of some kind
  • siblings/clones tour the galaxy giving technical help to collapsed societies
  • Is it allowed to use patents for new inventions?
  • Movie I saw in the 80s where a substance oozed off of movie stairs leaving a wet cat behind
  • Is there a phrase like "etymologically related" but for food?
  • Cryptic Clue Explanation: Tree that's sported to keep visitors out at university (3)
  • How to negotiate such toxic competitiveness during my master’s studies?
  • Is cellulose, blown-in insulation biodegradeable?
  • Lotto Number Generator - Javascript
  • Ubuntu Terminal with alternating colours for each line
  • Looking for some words or phrases

possibly incorrect assignment in c

Next: Options That Control Static Analysis , Previous: Options to Control Diagnostic Messages Formatting , Up: GCC Command Options   [ Contents ][ Index ]

3.8 Options to Request or Suppress Warnings ¶

Warnings are diagnostic messages that report constructions that are not inherently erroneous but that are risky or suggest there may have been an error.

The following language-independent options do not enable specific warnings but control the kinds of diagnostics produced by GCC.

Check the code for syntax errors, but don’t do anything beyond that.

Limits the maximum number of error messages to n , at which point GCC bails out rather than attempting to continue processing the source code. If n is 0 (the default), there is no limit on the number of error messages produced. If -Wfatal-errors is also specified, then -Wfatal-errors takes precedence over this option.

Inhibit all warning messages.

Make all warnings into errors.

Make the specified warning into an error. The specifier for a warning is appended; for example -Werror=switch turns the warnings controlled by -Wswitch into errors. This switch takes a negative form, to be used to negate -Werror for specific warnings; for example -Wno-error=switch makes -Wswitch warnings not be errors, even when -Werror is in effect.

The warning message for each controllable warning includes the option that controls the warning. That option can then be used with -Werror= and -Wno-error= as described above. (Printing of the option in the warning message can be disabled using the -fno-diagnostics-show-option flag.)

Note that specifying -Werror= foo automatically implies -W foo . However, -Wno-error= foo does not imply anything.

This option causes the compiler to abort compilation on the first error occurred rather than trying to keep going and printing further error messages.

You can request many specific warnings with options beginning with ‘ -W ’, for example -Wimplicit to request warnings on implicit declarations. Each of these specific warning options also has a negative form beginning ‘ -Wno- ’ to turn off warnings; for example, -Wno-implicit . This manual lists only one of the two forms, whichever is not the default. For further language-specific options also refer to Options Controlling C++ Dialect and Options Controlling Objective-C and Objective-C++ Dialects . Additional warnings can be produced by enabling the static analyzer; See Options That Control Static Analysis .

Some options, such as -Wall and -Wextra , turn on other options, such as -Wunused , which may turn on further options, such as -Wunused-value . The combined effect of positive and negative forms is that more specific options have priority over less specific ones, independently of their position in the command-line. For options of the same specificity, the last one takes effect. Options enabled or disabled via pragmas (see Diagnostic Pragmas ) take effect as if they appeared at the end of the command-line.

When an unrecognized warning option is requested (e.g., -Wunknown-warning ), GCC emits a diagnostic stating that the option is not recognized. However, if the -Wno- form is used, the behavior is slightly different: no diagnostic is produced for -Wno-unknown-warning unless other diagnostics are being produced. This allows the use of new -Wno- options with old compilers, but if something goes wrong, the compiler warns that an unrecognized option is present.

The effectiveness of some warnings depends on optimizations also being enabled. For example -Wsuggest-final-types is more effective with link-time optimization and some instances of other warnings may not be issued at all unless optimization is enabled. While optimization in general improves the efficacy of control and data flow sensitive warnings, in some cases it may also cause false positives.

Issue all the warnings demanded by strict ISO C and ISO C++; diagnose all programs that use forbidden extensions, and some other programs that do not follow ISO C and ISO C++. This follows the version of the ISO C or C++ standard specified by any -std option used.

Valid ISO C and ISO C++ programs should compile properly with or without this option (though a rare few require -ansi or a -std option specifying the version of the standard). However, without this option, certain GNU extensions and traditional C and C++ features are supported as well. With this option, they are diagnosed (or rejected with -pedantic-errors ).

-Wpedantic does not cause warning messages for use of the alternate keywords whose names begin and end with ‘ __ ’. This alternate format can also be used to disable warnings for non-ISO ‘ __intN ’ types, i.e. ‘ __intN__ ’. Pedantic warnings are also disabled in the expression that follows __extension__ . However, only system header files should use these escape routes; application programs should avoid them. See Alternate Keywords .

Some warnings about non-conforming programs are controlled by options other than -Wpedantic ; in many cases they are implied by -Wpedantic but can be disabled separately by their specific option, e.g. -Wpedantic -Wno-pointer-sign .

Where the standard specified with -std represents a GNU extended dialect of C, such as ‘ gnu90 ’ or ‘ gnu99 ’, there is a corresponding base standard , the version of ISO C on which the GNU extended dialect is based. Warnings from -Wpedantic are given where they are required by the base standard. (It does not make sense for such warnings to be given only for features not in the specified GNU C dialect, since by definition the GNU dialects of C include all features the compiler supports with the given option, and there would be nothing to warn about.)

Give an error whenever the base standard (see -Wpedantic ) requires a diagnostic, in some cases where there is undefined behavior at compile-time and in some other cases that do not prevent compilation of programs that are valid according to the standard. This is not equivalent to -Werror=pedantic : the latter option is unlikely to be useful, as it only makes errors of the diagnostics that are controlled by -Wpedantic , whereas this option also affects required diagnostics that are always enabled or controlled by options other than -Wpedantic .

If you want the required diagnostics that are warnings by default to be errors instead, but don’t also want to enable the -Wpedantic diagnostics, you can specify -pedantic-errors -Wno-pedantic (or -pedantic-errors -Wno-error=pedantic to enable them but only as warnings).

Some required diagnostics are errors by default, but can be reduced to warnings using -fpermissive or their specific warning option, e.g. -Wno-error=narrowing .

Some diagnostics for non-ISO practices are controlled by specific warning options other than -Wpedantic , but are also made errors by -pedantic-errors . For instance:

Downgrade some required diagnostics about nonconformant code from errors to warnings. Thus, using -fpermissive allows some nonconforming code to compile. Some C++ diagnostics are controlled only by this flag, but it also downgrades some C and C++ diagnostics that have their own flag:

The -fpermissive option is the default for historic C language modes ( -std=c89 , -std=gnu89 , -std=c90 , -std=gnu90 ).

This enables all the warnings about constructions that some users consider questionable, and that are easy to avoid (or modify to prevent the warning), even in conjunction with macros. This also enables some language-specific warnings described in Options Controlling C++ Dialect and Options Controlling Objective-C and Objective-C++ Dialects .

-Wall turns on the following warning flags:

Note that some warning flags are not implied by -Wall . Some of them warn about constructions that users generally do not consider questionable, but which occasionally you might wish to check for; others warn about constructions that are necessary or hard to avoid in some cases, and there is no simple way to modify the code to suppress the warning. Some of them are enabled by -Wextra but many of them must be enabled individually.

This enables some extra warning flags that are not enabled by -Wall . (This option used to be called -W . The older name is still supported, but the newer name is more descriptive.)

The option -Wextra also prints warning messages for the following cases:

  • A pointer is compared against integer zero with < , <= , > , or >= .
  • (C++ only) An enumerator and a non-enumerator both appear in a conditional expression.
  • (C++ only) Ambiguous virtual bases.
  • (C++ only) Subscripting an array that has been declared register .
  • (C++ only) Taking the address of a variable that has been declared register .
  • (C++ only) A base class is not initialized in the copy constructor of a derived class.

Warn about code affected by ABI changes. This includes code that may not be compatible with the vendor-neutral C++ ABI as well as the psABI for the particular target.

Since G++ now defaults to updating the ABI with each major release, normally -Wabi warns only about C++ ABI compatibility problems if there is a check added later in a release series for an ABI issue discovered since the initial release. -Wabi warns about more things if an older ABI version is selected (with -fabi-version= n ).

-Wabi can also be used with an explicit version number to warn about C++ ABI compatibility with a particular -fabi-version level, e.g. -Wabi=2 to warn about changes relative to -fabi-version=2 .

If an explicit version number is provided and -fabi-compat-version is not specified, the version number from this option is used for compatibility aliases. If no explicit version number is provided with this option, but -fabi-compat-version is specified, that version number is used for C++ ABI warnings.

Although an effort has been made to warn about all such cases, there are probably some cases that are not warned about, even though G++ is generating incompatible code. There may also be cases where warnings are emitted even though the code that is generated is compatible.

You should rewrite your code to avoid these warnings if you are concerned about the fact that code generated by G++ may not be binary compatible with code generated by other compilers.

Known incompatibilities in -fabi-version=2 (which was the default from GCC 3.4 to 4.9) include:

This was fixed in -fabi-version=3 .

The mangling was changed in -fabi-version=4 .

These mangling issues were fixed in -fabi-version=5 .

Also, the ABI changed the mangling of template argument packs, const_cast , static_cast , prefix increment/decrement, and a class scope function used as a template argument.

These issues were corrected in -fabi-version=6 .

These issues were corrected in -fabi-version=7 .

This was fixed in -fabi-version=8 , the default for GCC 5.1.

This was fixed in -fabi-version=9 , the default for GCC 5.2.

This was fixed in -fabi-version=10 , the default for GCC 6.1.

This option also enables warnings about psABI-related changes. The known psABI changes at this point include:

union U is now always passed in memory.

C++ requires that unqualified uses of a name within a class have the same meaning in the complete scope of the class, so declaring the name after using it is ill-formed:

By default, the B1 case is only a warning because the two declarations have the same type, while the B2 case is an error. Both diagnostics can be disabled with -Wno-changes-meaning . Alternately, the error case can be reduced to a warning with -Wno-error=changes-meaning or -fpermissive .

Both diagnostics are also suppressed by -fms-extensions .

Warn if an array subscript has type char . This is a common cause of error, as programmers often forget that this type is signed on some machines. This warning is enabled by -Wall .

Warn if feedback profiles do not match when using the -fprofile-use option. If a source file is changed between compiling with -fprofile-generate and with -fprofile-use , the files with the profile feedback can fail to match the source file and GCC cannot use the profile feedback information. By default, this warning is enabled and is treated as an error. -Wno-coverage-mismatch can be used to disable the warning or -Wno-error=coverage-mismatch can be used to disable the error. Disabling the error for this warning can result in poorly optimized code and is useful only in the case of very minor changes such as bug fixes to an existing code-base. Completely disabling the warning is not recommended.

Warn if -fcondition-coverage is used and an expression have too many terms and GCC gives up coverage. Coverage is given up when there are more terms in the conditional than there are bits in a gcov_type_unsigned . This warning is enabled by default.

Warn in case a function ends earlier than it begins due to an invalid linenum macros. The warning is emitted only with --coverage enabled.

By default, this warning is enabled and is treated as an error. -Wno-coverage-invalid-line-number can be used to disable the warning or -Wno-error=coverage-invalid-line-number can be used to disable the error.

Suppress warning messages emitted by #warning directives.

Give a warning when a value of type float is implicitly promoted to double . CPUs with a 32-bit “single-precision” floating-point unit implement float in hardware, but emulate double in software. On such a machine, doing computations using double values is much more expensive because of the overhead required for software emulation.

It is easy to accidentally do computations with double because floating-point literals are implicitly of type double . For example, in:

the compiler performs the entire computation with double because the floating-point literal is a double .

Warn if a declaration has duplicate const , volatile , restrict or _Atomic specifier. This warning is enabled by -Wall .

Check calls to printf and scanf , etc., to make sure that the arguments supplied have types appropriate to the format string specified, and that the conversions specified in the format string make sense. This includes standard functions, and others specified by format attributes (see Declaring Attributes of Functions ), in the printf , scanf , strftime and strfmon (an X/Open extension, not in the C standard) families (or other target-specific families). Which functions are checked without format attributes having been specified depends on the standard version selected, and such checks of functions without the attribute specified are disabled by -ffreestanding or -fno-builtin .

The formats are checked against the format features supported by GNU libc version 2.2. These include all ISO C90 and C99 features, as well as features from the Single Unix Specification and some BSD and GNU extensions. Other library implementations may not support all these features; GCC does not support warning about features that go beyond a particular library’s limitations. However, if -Wpedantic is used with -Wformat , warnings are given about format features not in the selected standard version (but not for strfmon formats, since those are not in any version of the C standard). See Options Controlling C Dialect .

Option -Wformat is equivalent to -Wformat=1 , and -Wno-format is equivalent to -Wformat=0 . Since -Wformat also checks for null format arguments for several functions, -Wformat also implies -Wnonnull . Some aspects of this level of format checking can be disabled by the options: -Wno-format-contains-nul , -Wno-format-extra-args , and -Wno-format-zero-length . -Wformat is enabled by -Wall .

Enable -Wformat plus additional format checks. Currently equivalent to -Wformat -Wformat-nonliteral -Wformat-security -Wformat-y2k .

If -Wformat is specified, do not warn about format strings that contain NUL bytes.

If -Wformat is specified, do not warn about excess arguments to a printf or scanf format function. The C standard specifies that such arguments are ignored.

Where the unused arguments lie between used arguments that are specified with ‘ $ ’ operand number specifications, normally warnings are still given, since the implementation could not know what type to pass to va_arg to skip the unused arguments. However, in the case of scanf formats, this option suppresses the warning if the unused arguments are all pointers, since the Single Unix Specification says that such unused arguments are allowed.

Warn about calls to formatted input/output functions such as sprintf and vsprintf that might overflow the destination buffer. When the exact number of bytes written by a format directive cannot be determined at compile-time it is estimated based on heuristics that depend on the level argument and on optimization. While enabling optimization will in most cases improve the accuracy of the warning, it may also result in false positives.

Level 1 of -Wformat-overflow enabled by -Wformat employs a conservative approach that warns only about calls that most likely overflow the buffer. At this level, numeric arguments to format directives with unknown values are assumed to have the value of one, and strings of unknown length to be empty. Numeric arguments that are known to be bounded to a subrange of their type, or string arguments whose output is bounded either by their directive’s precision or by a finite set of string literals, are assumed to take on the value within the range that results in the most bytes on output. For example, the call to sprintf below is diagnosed because even with both a and b equal to zero, the terminating NUL character ( '\0' ) appended by the function to the destination buffer will be written past its end. Increasing the size of the buffer by a single byte is sufficient to avoid the warning, though it may not be sufficient to avoid the overflow.

Level 2 warns also about calls that might overflow the destination buffer given an argument of sufficient length or magnitude. At level 2 , unknown numeric arguments are assumed to have the minimum representable value for signed types with a precision greater than 1, and the maximum representable value otherwise. Unknown string arguments whose length cannot be assumed to be bounded either by the directive’s precision, or by a finite set of string literals they may evaluate to, or the character array they may point to, are assumed to be 1 character long.

At level 2 , the call in the example above is again diagnosed, but this time because with a equal to a 32-bit INT_MIN the first %i directive will write some of its digits beyond the end of the destination buffer. To make the call safe regardless of the values of the two variables, the size of the destination buffer must be increased to at least 34 bytes. GCC includes the minimum size of the buffer in an informational note following the warning.

An alternative to increasing the size of the destination buffer is to constrain the range of formatted values. The maximum length of string arguments can be bounded by specifying the precision in the format directive. When numeric arguments of format directives can be assumed to be bounded by less than the precision of their type, choosing an appropriate length modifier to the format specifier will reduce the required buffer size. For example, if a and b in the example above can be assumed to be within the precision of the short int type then using either the %hi format directive or casting the argument to short reduces the maximum required size of the buffer to 24 bytes.

If -Wformat is specified, do not warn about zero-length formats. The C standard specifies that zero-length formats are allowed.

If -Wformat is specified, also warn if the format string is not a string literal and so cannot be checked, unless the format function takes its format arguments as a va_list .

If -Wformat is specified, also warn about uses of format functions that represent possible security problems. At present, this warns about calls to printf and scanf functions where the format string is not a string literal and there are no format arguments, as in printf (foo); . This may be a security hole if the format string came from untrusted input and contains ‘ %n ’. (This is currently a subset of what -Wformat-nonliteral warns about, but in future warnings may be added to -Wformat-security that are not included in -Wformat-nonliteral .)

If -Wformat is specified, also warn if the format string requires an unsigned argument and the argument is signed and vice versa.

Warn about calls to formatted input/output functions such as snprintf and vsnprintf that might result in output truncation. When the exact number of bytes written by a format directive cannot be determined at compile-time it is estimated based on heuristics that depend on the level argument and on optimization. While enabling optimization will in most cases improve the accuracy of the warning, it may also result in false positives. Except as noted otherwise, the option uses the same logic -Wformat-overflow .

Level 1 of -Wformat-truncation enabled by -Wformat employs a conservative approach that warns only about calls to bounded functions whose return value is unused and that will most likely result in output truncation.

Level 2 warns also about calls to bounded functions whose return value is used and that might result in truncation given an argument of sufficient length or magnitude.

If -Wformat is specified, also warn about strftime formats that may yield only a two-digit year.

Warn about passing a null pointer for arguments marked as requiring a non-null value by the nonnull function attribute.

-Wnonnull is included in -Wall and -Wformat . It can be disabled with the -Wno-nonnull option.

Warn when comparing an argument marked with the nonnull function attribute against null inside the function.

-Wnonnull-compare is included in -Wall . It can be disabled with the -Wno-nonnull-compare option.

Warn if the compiler detects paths that trigger erroneous or undefined behavior due to dereferencing a null pointer. This option is only active when -fdelete-null-pointer-checks is active, which is enabled by optimizations in most targets. The precision of the warnings depends on the optimization options used.

Warn if the compiler does not elide the copy from a local variable to the return value of a function in a context where it is allowed by [class.copy.elision]. This elision is commonly known as the Named Return Value Optimization. For instance, in the example below the compiler cannot elide copies from both v1 and v2, so it elides neither.

Warn about infinitely recursive calls. The warning is effective at all optimization levels but requires optimization in order to detect infinite recursion in calls between two or more functions. -Winfinite-recursion is included in -Wall .

Compare with -Wanalyzer-infinite-recursion which provides a similar diagnostic, but is implemented in a different way (as part of -fanalyzer ).

Warn about uninitialized variables that are initialized with themselves. Note this option can only be used with the -Wuninitialized option.

For example, GCC warns about i being uninitialized in the following snippet only when -Winit-self has been specified:

This warning is enabled by -Wall in C++.

This option controls warnings when a declaration does not specify a type. This warning is enabled by default, as an error, in C99 and later dialects of C, and also by -Wall . The error can be downgraded to a warning using -fpermissive (along with certain other errors), or for this error alone, with -Wno-error=implicit-int .

This warning is upgraded to an error by -pedantic-errors .

This option controls warnings when a function is used before being declared. This warning is enabled by default, as an error, in C99 and later dialects of C, and also by -Wall . The error can be downgraded to a warning using -fpermissive (along with certain other errors), or for this error alone, with -Wno-error=implicit-function-declaration .

Same as -Wimplicit-int and -Wimplicit-function-declaration . This warning is enabled by -Wall .

Warn when -fhardened did not enable an option from its set (for which see -fhardened ). For instance, using -fhardened and -fstack-protector at the same time on the command line causes -Whardened to warn because -fstack-protector-strong is not enabled by -fhardened .

This warning is enabled by default and has effect only when -fhardened is enabled.

-Wimplicit-fallthrough is the same as -Wimplicit-fallthrough=3 and -Wno-implicit-fallthrough is the same as -Wimplicit-fallthrough=0 .

Warn when a switch case falls through. For example:

This warning does not warn when the last statement of a case cannot fall through, e.g. when there is a return statement or a call to function declared with the noreturn attribute. -Wimplicit-fallthrough= also takes into account control flow statements, such as ifs, and only warns when appropriate. E.g.

Since there are occasions where a switch case fall through is desirable, GCC provides an attribute, __attribute__ ((fallthrough)) , that is to be used along with a null statement to suppress this warning that would normally occur:

C++17 provides a standard way to suppress the -Wimplicit-fallthrough warning using [[fallthrough]]; instead of the GNU attribute. In C++11 or C++14 users can use [[gnu::fallthrough]]; , which is a GNU extension. Instead of these attributes, it is also possible to add a fallthrough comment to silence the warning. The whole body of the C or C++ style comment should match the given regular expressions listed below. The option argument n specifies what kind of comments are accepted:

  • -Wimplicit-fallthrough=0 disables the warning altogether.
  • -Wimplicit-fallthrough=1 matches .* regular expression, any comment is used as fallthrough comment.
  • -Wimplicit-fallthrough=2 case insensitively matches .*falls?[ \t-]*thr(ough|u).* regular expression.
  • -fallthrough
  • @fallthrough@
  • lint -fallthrough[ \t]*
  • [ \t.!]*(ELSE,? |INTENTIONAL(LY)? )? FALL(S | |-)?THR(OUGH|U)[ \t.!]*(-[^\n\r]*)?
  • [ \t.!]*(Else,? |Intentional(ly)? )? Fall((s | |-)[Tt]|t)hr(ough|u)[ \t.!]*(-[^\n\r]*)?
  • [ \t.!]*([Ee]lse,? |[Ii]ntentional(ly)? )? fall(s | |-)?thr(ough|u)[ \t.!]*(-[^\n\r]*)?
  • [ \t]*FALLTHR(OUGH|U)[ \t]*
  • -Wimplicit-fallthrough=5 doesn’t recognize any comments as fallthrough comments, only attributes disable the warning.

The comment needs to be followed after optional whitespace and other comments by case or default keywords or by a user label that precedes some case or default label.

The -Wimplicit-fallthrough=3 warning is enabled by -Wextra .

Control if warnings triggered by the warn_if_not_aligned attribute should be issued. These warnings are enabled by default.

Warn if the return type of a function has a type qualifier such as const . For ISO C such a type qualifier has no effect, since the value returned by a function is not an lvalue. For C++, the warning is only emitted for scalar types or void . ISO C prohibits qualified void return types on function definitions, so such return types always receive a warning even without this option.

This warning is also enabled by -Wextra .

This option controls warnings when an attribute is ignored. This is different from the -Wattributes option in that it warns whenever the compiler decides to drop an attribute, not that the attribute is either unknown, used in a wrong place, etc. This warning is enabled by default.

Warn if the type of main is suspicious. main should be a function with external linkage, returning int, taking either zero arguments, two, or three arguments of appropriate types. This warning is enabled by default in C++ and is enabled by either -Wall or -Wpedantic .

Warn when the indentation of the code does not reflect the block structure. Specifically, a warning is issued for if , else , while , and for clauses with a guarded statement that does not use braces, followed by an unguarded statement with the same indentation.

In the following example, the call to “bar” is misleadingly indented as if it were guarded by the “if” conditional.

In the case of mixed tabs and spaces, the warning uses the -ftabstop= option to determine if the statements line up (defaulting to 8).

The warning is not issued for code involving multiline preprocessor logic such as the following example.

The warning is not issued after a #line directive, since this typically indicates autogenerated code, and no assumptions can be made about the layout of the file that the directive references.

This warning is enabled by -Wall in C and C++.

Warn when a declaration of a function is missing one or more attributes that a related function is declared with and whose absence may adversely affect the correctness or efficiency of generated code. For example, the warning is issued for declarations of aliases that use attributes to specify less restrictive requirements than those of their targets. This typically represents a potential optimization opportunity. By contrast, the -Wattribute-alias=2 option controls warnings issued when the alias is more restrictive than the target, which could lead to incorrect code generation. Attributes considered include alloc_align , alloc_size , cold , const , hot , leaf , malloc , nonnull , noreturn , nothrow , pure , returns_nonnull , and returns_twice .

In C++, the warning is issued when an explicit specialization of a primary template declared with attribute alloc_align , alloc_size , assume_aligned , format , format_arg , malloc , or nonnull is declared without it. Attributes deprecated , error , and warning suppress the warning. (see Declaring Attributes of Functions ).

You can use the copy attribute to apply the same set of attributes to a declaration as that on another declaration without explicitly enumerating the attributes. This attribute can be applied to declarations of functions (see Common Function Attributes ), variables (see Common Variable Attributes ), or types (see Common Type Attributes ).

-Wmissing-attributes is enabled by -Wall .

For example, since the declaration of the primary function template below makes use of both attribute malloc and alloc_size the declaration of the explicit specialization of the template is diagnosed because it is missing one of the attributes.

Warn if an aggregate or union initializer is not fully bracketed. In the following example, the initializer for a is not fully bracketed, but that for b is fully bracketed.

This warning is enabled by -Wall .

Warn if a user-supplied include directory does not exist. This option is disabled by default for C, C++, Objective-C and Objective-C++. For Fortran, it is partially enabled by default by warning for -I and -J, only.

This option controls warnings if feedback profiles are missing when using the -fprofile-use option. This option diagnoses those cases where a new function or a new file is added between compiling with -fprofile-generate and with -fprofile-use , without regenerating the profiles. In these cases, the profile feedback data files do not contain any profile feedback information for the newly added function or file respectively. Also, in the case when profile count data (.gcda) files are removed, GCC cannot use any profile feedback information. In all these cases, warnings are issued to inform you that a profile generation step is due. Ignoring the warning can result in poorly optimized code. -Wno-missing-profile can be used to disable the warning, but this is not recommended and should be done only when non-existent profile data is justified.

Warn for calls to deallocation functions with pointer arguments returned from allocation functions for which the former isn’t a suitable deallocator. A pair of functions can be associated as matching allocators and deallocators by use of attribute malloc . Unless disabled by the -fno-builtin option the standard functions calloc , malloc , realloc , and free , as well as the corresponding forms of C++ operator new and operator delete are implicitly associated as matching allocators and deallocators. In the following example mydealloc is the deallocator for pointers returned from myalloc .

In C++, the related option -Wmismatched-new-delete diagnoses mismatches involving either operator new or operator delete .

Option -Wmismatched-dealloc is included in -Wall .

Warn about unsafe multiple statement macros that appear to be guarded by a clause such as if , else , for , switch , or while , in which only the first statement is actually guarded after the macro is expanded.

For example:

will increment y unconditionally, not just when c holds. The can usually be fixed by wrapping the macro in a do-while loop:

Warn if parentheses are omitted in certain contexts, such as when there is an assignment in a context where a truth value is expected, or when operators are nested whose precedence people often get confused about.

Also warn if a comparison like x<=y<=z appears; this is equivalent to (x<=y ? 1 : 0) <= z , which is a different interpretation from that of ordinary mathematical notation.

Also warn for dangerous uses of the GNU extension to ?: with omitted middle operand. When the condition in the ? : operator is a boolean expression, the omitted value is always 1. Often programmers expect it to be a value computed inside the conditional expression instead.

For C++ this also warns for some cases of unnecessary parentheses in declarations, which can indicate an attempt at a function call instead of a declaration:

This warning warns when a value is moved to itself with std::move . Such a std::move typically has no effect.

Warn about code that may have undefined semantics because of violations of sequence point rules in the C and C++ standards.

The C and C++ standards define the order in which expressions in a C/C++ program are evaluated in terms of sequence points , which represent a partial ordering between the execution of parts of the program: those executed before the sequence point, and those executed after it. These occur after the evaluation of a full expression (one which is not part of a larger expression), after the evaluation of the first operand of a && , || , ? : or , (comma) operator, before a function is called (but after the evaluation of its arguments and the expression denoting the called function), and in certain other places. Other than as expressed by the sequence point rules, the order of evaluation of subexpressions of an expression is not specified. All these rules describe only a partial order rather than a total order, since, for example, if two functions are called within one expression with no sequence point between them, the order in which the functions are called is not specified. However, the standards committee have ruled that function calls do not overlap.

It is not specified when between sequence points modifications to the values of objects take effect. Programs whose behavior depends on this have undefined behavior; the C and C++ standards specify that “Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be read only to determine the value to be stored.”. If a program breaks these rules, the results on any particular implementation are entirely unpredictable.

Examples of code with undefined behavior are a = a++; , a[n] = b[n++] and a[i++] = i; . Some more complicated cases are not diagnosed by this option, and it may give an occasional false positive result, but in general it has been found fairly effective at detecting this sort of problem in programs.

The C++17 standard will define the order of evaluation of operands in more cases: in particular it requires that the right-hand side of an assignment be evaluated before the left-hand side, so the above examples are no longer undefined. But this option will still warn about them, to help people avoid writing code that is undefined in C and earlier revisions of C++.

The standard is worded confusingly, therefore there is some debate over the precise meaning of the sequence point rules in subtle cases. Links to discussions of the problem, including proposed formal definitions, may be found on the GCC readings page, at https://gcc.gnu.org/readings.html .

This warning is enabled by -Wall for C and C++.

Do not warn about returning a pointer (or in C++, a reference) to a variable that goes out of scope after the function returns.

Warn about return statements without an expressions in functions which do not return void . Also warn about a return statement with an expression in a function whose return type is void , unless the expression type is also void . As a GNU extension, the latter case is accepted without a warning unless -Wpedantic is used.

Attempting to use the return value of a non- void function other than main that flows off the end by reaching the closing curly brace that terminates the function is undefined.

This warning is specific to C and enabled by default. In C99 and later language dialects, it is treated as an error. It can be downgraded to a warning using -fpermissive (along with other warnings), or for just this warning, with -Wno-error=return-mismatch .

Warn whenever a function is defined with a return type that defaults to int (unless -Wimplicit-int is active, which takes precedence). Also warn if execution may reach the end of the function body, or if the function does not contain any return statement at all.

Unlike in C, in C++, flowing off the end of a non- void function other than main results in undefined behavior even when the value of the function is not used.

This warning is enabled by default in C++ and by -Wall otherwise.

Controls warnings if a shift count is negative. This warning is enabled by default.

Controls warnings if a shift count is greater than or equal to the bit width of the type. This warning is enabled by default.

Warn if left shifting a negative value. This warning is enabled by -Wextra in C99 (and newer) and C++11 to C++17 modes.

These options control warnings about left shift overflows.

This is the warning level of -Wshift-overflow and is enabled by default in C99 and C++11 modes (and newer). This warning level does not warn about left-shifting 1 into the sign bit. (However, in C, such an overflow is still rejected in contexts where an integer constant expression is required.) No warning is emitted in C++20 mode (and newer), as signed left shifts always wrap.

This warning level also warns about left-shifting 1 into the sign bit, unless C++14 mode (or newer) is active.

Warn whenever a switch statement has an index of enumerated type and lacks a case for one or more of the named codes of that enumeration. (The presence of a default label prevents this warning.) case labels outside the enumeration range also provoke warnings when this option is used (even if there is a default label). This warning is enabled by -Wall .

Warn whenever a switch statement does not have a default case.

Warn whenever a switch statement has an index of enumerated type and lacks a case for one or more of the named codes of that enumeration. case labels outside the enumeration range also provoke warnings when this option is used. The only difference between -Wswitch and this option is that this option gives a warning about an omitted enumeration code even if there is a default label.

Do not warn when a switch statement has an index of boolean type and the case values are outside the range of a boolean type. It is possible to suppress this warning by casting the controlling expression to a type other than bool . For example:

This warning is enabled by default for C and C++ programs.

This option controls warnings when a switch case has a value that is outside of its respective type range. This warning is enabled by default for C and C++ programs.

Do not warn when a switch statement contains statements between the controlling expression and the first case label, which will never be executed. For example:

-Wswitch-unreachable does not warn if the statement between the controlling expression and the first case label is just a declaration:

Warn when __sync_fetch_and_nand and __sync_nand_and_fetch built-in functions are used. These functions changed semantics in GCC 4.4.

Warn when -ftrivial-auto-var-init cannot initialize the automatic variable. A common situation is an automatic variable that is declared between the controlling expression and the first case label of a switch statement.

Warn whenever a function parameter is assigned to, but otherwise unused (aside from its declaration).

To suppress this warning use the unused attribute (see Specifying Attributes of Variables ).

This warning is also enabled by -Wunused together with -Wextra .

Warn whenever a local variable is assigned to, but otherwise unused (aside from its declaration). This warning is enabled by -Wall .

This warning is also enabled by -Wunused , which is enabled by -Wall .

Warn whenever a static function is declared but not defined or a non-inline static function is unused. This warning is enabled by -Wall .

Warn whenever a label is declared but not used. This warning is enabled by -Wall .

Warn when a typedef locally defined in a function is not used. This warning is enabled by -Wall .

Warn whenever a function parameter is unused aside from its declaration. This option is not enabled by -Wunused unless -Wextra is also specified.

Do not warn if a caller of a function marked with attribute warn_unused_result (see Declaring Attributes of Functions ) does not use its return value. The default is -Wunused-result .

Warn whenever a local or static variable is unused aside from its declaration. This option implies -Wunused-const-variable=1 for C, but not for C++. This warning is enabled by -Wall .

Warn whenever a constant static variable is unused aside from its declaration.

Warn about unused static const variables defined in the main compilation unit, but not about static const variables declared in any header included.

-Wunused-const-variable=1 is enabled by either -Wunused-variable or -Wunused for C, but not for C++. In C this declares variable storage, but in C++ this is not an error since const variables take the place of #define s.

This warning level also warns for unused constant static variables in headers (excluding system headers). It is equivalent to the short form -Wunused-const-variable . This level must be explicitly requested in both C and C++ because it might be hard to clean up all headers included.

Warn whenever a statement computes a result that is explicitly not used. To suppress this warning cast the unused expression to void . This includes an expression-statement or the left-hand side of a comma expression that contains no side effects. For example, an expression such as x[i,j] causes a warning, while x[(void)i,j] does not.

All the above -Wunused options combined, except those documented as needing to be specified explicitly.

In order to get a warning about an unused function parameter, you must either specify -Wextra -Wunused (note that -Wall implies -Wunused ), or separately specify -Wunused-parameter and/or -Wunused-but-set-parameter .

-Wunused enables only -Wunused-const-variable=1 rather than -Wunused-const-variable , and only for C, not C++.

Warn about uses of pointers to dynamically allocated objects that have been rendered indeterminate by a call to a deallocation function. The warning is enabled at all optimization levels but may yield different results with optimization than without.

At level 1 the warning attempts to diagnose only unconditional uses of pointers made indeterminate by a deallocation call or a successful call to realloc , regardless of whether or not the call resulted in an actual reallocation of memory. This includes double- free calls as well as uses in arithmetic and relational expressions. Although undefined, uses of indeterminate pointers in equality (or inequality) expressions are not diagnosed at this level.

At level 2, in addition to unconditional uses, the warning also diagnoses conditional uses of pointers made indeterminate by a deallocation call. As at level 2, uses in equality (or inequality) expressions are not diagnosed. For example, the second call to free in the following function is diagnosed at this level:

At level 3, the warning also diagnoses uses of indeterminate pointers in equality expressions. All uses of indeterminate pointers are undefined but equality tests sometimes appear after calls to realloc as an attempt to determine whether the call resulted in relocating the object to a different address. They are diagnosed at a separate level to aid gradually transitioning legacy code to safe alternatives. For example, the equality test in the function below is diagnosed at this level:

To avoid the warning at this level, store offsets into allocated memory instead of pointers. This approach obviates needing to adjust the stored pointers after reallocation.

-Wuse-after-free=2 is included in -Wall .

Warn when an expression is cast to its own type. This warning does not occur when a class object is converted to a non-reference type as that is a way to create a temporary:

Warn if an object with automatic or allocated storage duration is used without having been initialized. In C++, also warn if a non-static reference or non-static const member appears in a class without constructors.

In addition, passing a pointer (or in C++, a reference) to an uninitialized object to a const -qualified argument of a built-in function known to read the object is also diagnosed by this warning. ( -Wmaybe-uninitialized is issued for ordinary functions.)

If you want to warn about code that uses the uninitialized value of the variable in its own initializer, use the -Winit-self option.

These warnings occur for individual uninitialized elements of structure, union or array variables as well as for variables that are uninitialized as a whole. They do not occur for variables or elements declared volatile . Because these warnings depend on optimization, the exact variables or elements for which there are warnings depend on the precise optimization options and version of GCC used.

Note that there may be no warning about a variable that is used only to compute a value that itself is never used, because such computations may be deleted by data flow analysis before the warnings are printed.

In C++, this warning also warns about using uninitialized objects in member-initializer-lists. For example, GCC warns about b being uninitialized in the following snippet:

This option controls warnings for invocations of Built-in Functions for Memory Model Aware Atomic Operations , Legacy __sync Built-in Functions for Atomic Memory Access , and the C11 atomic generic functions with a memory consistency argument that is either invalid for the operation or outside the range of values of the memory_order enumeration. For example, since the __atomic_store and __atomic_store_n built-ins are only defined for the relaxed, release, and sequentially consistent memory orders the following code is diagnosed:

-Winvalid-memory-model is enabled by default.

For an object with automatic or allocated storage duration, if there exists a path from the function entry to a use of the object that is initialized, but there exist some other paths for which the object is not initialized, the compiler emits a warning if it cannot prove the uninitialized paths are not executed at run time.

In addition, passing a pointer (or in C++, a reference) to an uninitialized object to a const -qualified function argument is also diagnosed by this warning. ( -Wuninitialized is issued for built-in functions known to read the object.) Annotating the function with attribute access (none) indicates that the argument isn’t used to access the object and avoids the warning (see Common Function Attributes ).

These warnings are only possible in optimizing compilation, because otherwise GCC does not keep track of the state of variables.

These warnings are made optional because GCC may not be able to determine when the code is correct in spite of appearing to have an error. Here is one example of how this can happen:

If the value of y is always 1, 2 or 3, then x is always initialized, but GCC doesn’t know this. To suppress the warning, you need to provide a default case with assert(0) or similar code.

This option also warns when a non-volatile automatic variable might be changed by a call to longjmp . The compiler sees only the calls to setjmp . It cannot know where longjmp will be called; in fact, a signal handler could call it at any point in the code. As a result, you may get a warning even when there is in fact no problem because longjmp cannot in fact be called at the place that would cause a problem.

Some spurious warnings can be avoided if you declare all the functions you use that never return as noreturn . See Declaring Attributes of Functions .

This warning is enabled by -Wall or -Wextra .

Warn when a #pragma directive is encountered that is not understood by GCC. If this command-line option is used, warnings are even issued for unknown pragmas in system header files. This is not the case if the warnings are only enabled by the -Wall command-line option.

Do not warn about misuses of pragmas, such as incorrect parameters, invalid syntax, or conflicts between pragmas. See also -Wunknown-pragmas .

Do not warn if a priority from 0 to 100 is used for constructor or destructor. The use of constructor and destructor attributes allow you to assign a priority to the constructor/destructor to control its order of execution before main is called or after it returns. The priority values must be greater than 100 as the compiler reserves priority values between 0–100 for the implementation.

This option is only active when -fstrict-aliasing is active. It warns about code that might break the strict aliasing rules that the compiler is using for optimization. The warning does not catch all cases, but does attempt to catch the more common pitfalls. It is included in -Wall . It is equivalent to -Wstrict-aliasing=3

This option is only active when -fstrict-aliasing is active. It warns about code that might break the strict aliasing rules that the compiler is using for optimization. Higher levels correspond to higher accuracy (fewer false positives). Higher levels also correspond to more effort, similar to the way -O works. -Wstrict-aliasing is equivalent to -Wstrict-aliasing=3 .

Level 1: Most aggressive, quick, least accurate. Possibly useful when higher levels do not warn but -fstrict-aliasing still breaks the code, as it has very few false negatives. However, it has many false positives. Warns for all pointer conversions between possibly incompatible types, even if never dereferenced. Runs in the front end only.

Level 2: Aggressive, quick, not too precise. May still have many false positives (not as many as level 1 though), and few false negatives (but possibly more than level 1). Unlike level 1, it only warns when an address is taken. Warns about incomplete types. Runs in the front end only.

Level 3 (default for -Wstrict-aliasing ): Should have very few false positives and few false negatives. Slightly slower than levels 1 or 2 when optimization is enabled. Takes care of the common pun+dereference pattern in the front end: *(int*)&some_float . If optimization is enabled, it also runs in the back end, where it deals with multiple statement cases using flow-sensitive points-to information. Only warns when the converted pointer is dereferenced. Does not warn about incomplete types.

This option is only active when signed overflow is undefined. It warns about cases where the compiler optimizes based on the assumption that signed overflow does not occur. Note that it does not warn about all cases where the code might overflow: it only warns about cases where the compiler implements some optimization. Thus this warning depends on the optimization level.

An optimization that assumes that signed overflow does not occur is perfectly safe if the values of the variables involved are such that overflow never does, in fact, occur. Therefore this warning can easily give a false positive: a warning about code that is not actually a problem. To help focus on important issues, several warning levels are defined. No warnings are issued for the use of undefined signed overflow when estimating how many iterations a loop requires, in particular when determining whether a loop will be executed at all.

Warn about cases that are both questionable and easy to avoid. For example the compiler simplifies x + 1 > x to 1 . This level of -Wstrict-overflow is enabled by -Wall ; higher levels are not, and must be explicitly requested.

Also warn about other cases where a comparison is simplified to a constant. For example: abs (x) >= 0 . This can only be simplified when signed integer overflow is undefined, because abs (INT_MIN) overflows to INT_MIN , which is less than zero. -Wstrict-overflow (with no level) is the same as -Wstrict-overflow=2 .

Also warn about other cases where a comparison is simplified. For example: x + 1 > 1 is simplified to x > 0 .

Also warn about other simplifications not covered by the above cases. For example: (x * 10) / 5 is simplified to x * 2 .

Also warn about cases where the compiler reduces the magnitude of a constant involved in a comparison. For example: x + 2 > y is simplified to x + 1 >= y . This is reported only at the highest warning level because this simplification applies to many comparisons, so this warning level gives a very large number of false positives.

Warn for calls to strcmp and strncmp whose result is determined to be either zero or non-zero in tests for such equality owing to the length of one argument being greater than the size of the array the other argument is stored in (or the bound in the case of strncmp ). Such calls could be mistakes. For example, the call to strcmp below is diagnosed because its result is necessarily non-zero irrespective of the contents of the array a .

-Wstring-compare is enabled by -Wextra .

Warn for calls to string manipulation functions such as memcpy and strcpy that are determined to overflow the destination buffer. The optional argument is one greater than the type of Object Size Checking to perform to determine the size of the destination. See Object Size Checking . The argument is meaningful only for functions that operate on character arrays but not for raw memory functions like memcpy which always make use of Object Size type-0. The option also warns for calls that specify a size in excess of the largest possible object or at most SIZE_MAX / 2 bytes. The option produces the best results with optimization enabled but can detect a small subset of simple buffer overflows even without optimization in calls to the GCC built-in functions like __builtin_memcpy that correspond to the standard functions. In any case, the option warns about just a subset of buffer overflows detected by the corresponding overflow checking built-ins. For example, the option issues a warning for the strcpy call below because it copies at least 5 characters (the string "blue" including the terminating NUL) into the buffer of size 4.

Option -Wstringop-overflow=2 is enabled by default.

The -Wstringop-overflow=1 option uses type-zero Object Size Checking to determine the sizes of destination objects. At this setting the option does not warn for writes past the end of subobjects of larger objects accessed by pointers unless the size of the largest surrounding object is known. When the destination may be one of several objects it is assumed to be the largest one of them. On Linux systems, when optimization is enabled at this setting the option warns for the same code as when the _FORTIFY_SOURCE macro is defined to a non-zero value.

The -Wstringop-overflow=2 option uses type-one Object Size Checking to determine the sizes of destination objects. At this setting the option warns about overflows when writing to members of the largest complete objects whose exact size is known. However, it does not warn for excessive writes to the same members of unknown objects referenced by pointers since they may point to arrays containing unknown numbers of elements. This is the default setting of the option.

The -Wstringop-overflow=3 option uses type-two Object Size Checking to determine the sizes of destination objects. At this setting the option warns about overflowing the smallest object or data member. This is the most restrictive setting of the option that may result in warnings for safe code.

The -Wstringop-overflow=4 option uses type-three Object Size Checking to determine the sizes of destination objects. At this setting the option warns about overflowing any data members, and when the destination is one of several objects it uses the size of the largest of them to decide whether to issue a warning. Similarly to -Wstringop-overflow=3 this setting of the option may result in warnings for benign code.

Warn for calls to string manipulation functions such as memchr , or strcpy that are determined to read past the end of the source sequence.

Option -Wstringop-overread is enabled by default.

Do not warn for calls to bounded string manipulation functions such as strncat , strncpy , and stpncpy that may either truncate the copied string or leave the destination unchanged.

In the following example, the call to strncat specifies a bound that is less than the length of the source string. As a result, the copy of the source will be truncated and so the call is diagnosed. To avoid the warning use bufsize - strlen (buf) - 1) as the bound.

As another example, the following call to strncpy results in copying to d just the characters preceding the terminating NUL, without appending the NUL to the end. Assuming the result of strncpy is necessarily a NUL-terminated string is a common mistake, and so the call is diagnosed. To avoid the warning when the result is not expected to be NUL-terminated, call memcpy instead.

In the following example, the call to strncpy specifies the size of the destination buffer as the bound. If the length of the source string is equal to or greater than this size the result of the copy will not be NUL-terminated. Therefore, the call is also diagnosed. To avoid the warning, specify sizeof buf - 1 as the bound and set the last element of the buffer to NUL .

In situations where a character array is intended to store a sequence of bytes with no terminating NUL such an array may be annotated with attribute nonstring to avoid this warning. Such arrays, however, are not suitable arguments to functions that expect NUL -terminated strings. To help detect accidental misuses of such arrays GCC issues warnings unless it can prove that the use is safe. See Common Variable Attributes .

Warn about improper usages of flexible array members according to the level of the strict_flex_array ( level ) attribute attached to the trailing array field of a structure if it’s available, otherwise according to the level of the option -fstrict-flex-arrays= level . See Common Variable Attributes , for more information about the attribute, and Options Controlling C Dialect for more information about the option. -Wstrict-flex-arrays is effective only when level is greater than 0.

When level =1, warnings are issued for a trailing array reference of a structure that have 2 or more elements if the trailing array is referenced as a flexible array member.

When level =2, in addition to level =1, additional warnings are issued for a trailing one-element array reference of a structure if the array is referenced as a flexible array member.

When level =3, in addition to level =2, additional warnings are issued for a trailing zero-length array reference of a structure if the array is referenced as a flexible array member.

This option is more effective when -ftree-vrp is active (the default for -O2 and above) but some warnings may be diagnosed even without optimization.

Warn for cases where adding an attribute may be beneficial. The attributes currently supported are listed below.

Warn about functions that might be candidates for attributes pure , const , noreturn , malloc or returns_nonnull . The compiler only warns for functions visible in other compilation units or (in the case of pure and const ) if it cannot prove that the function returns normally. A function returns normally if it doesn’t contain an infinite loop or return abnormally by throwing, calling abort or trapping. This analysis requires option -fipa-pure-const , which is enabled by default at -O and higher. Higher optimization levels improve the accuracy of the analysis.

Warn about function pointers that might be candidates for format attributes. Note these are only possible candidates, not absolute ones. GCC guesses that function pointers with format attributes that are used in assignment, initialization, parameter passing or return statements should have a corresponding format attribute in the resulting type. I.e. the left-hand side of the assignment or initialization, the type of the parameter variable, or the return type of the containing function respectively should also have a format attribute to avoid the warning.

GCC also warns about function definitions that might be candidates for format attributes. Again, these are only possible candidates. GCC guesses that format attributes might be appropriate for any function that calls a function like vprintf or vscanf , but this might not always be the case, and some functions for which format attributes are appropriate may not be detected.

Warn about functions that might be candidates for cold attribute. This is based on static detection and generally only warns about functions which always leads to a call to another cold function such as wrappers of C++ throw or fatal error reporting functions leading to abort .

Warn about calls to allocation functions decorated with attribute alloc_size that specify insufficient size for the target type of the pointer the result is assigned to, including those to the built-in forms of the functions aligned_alloc , alloca , calloc , malloc , and realloc .

Warn about calls to allocation functions decorated with attribute alloc_size that specify zero bytes, including those to the built-in forms of the functions aligned_alloc , alloca , calloc , malloc , and realloc . Because the behavior of these functions when called with a zero size differs among implementations (and in the case of realloc has been deprecated) relying on it may result in subtle portability bugs and should be avoided.

Warn about calls to allocation functions decorated with attribute alloc_size with two arguments, which use sizeof operator as the earlier size argument and don’t use it as the later size argument. This is a coding style warning. The first argument to calloc is documented to be number of elements in array, while the second argument is size of each element, so calloc ( n , sizeof (int)) is preferred over calloc (sizeof (int), n ) . If sizeof in the earlier argument and not the latter is intentional, the warning can be suppressed by using calloc (sizeof (struct S ) + 0, n) or calloc (1 * sizeof (struct S ), 4) or using sizeof in the later argument as well.

Warn about calls to functions decorated with attribute alloc_size that attempt to allocate objects larger than the specified number of bytes, or where the result of the size computation in an integer type with infinite precision would exceed the value of ‘ PTRDIFF_MAX ’ on the target. -Walloc-size-larger-than= ‘ PTRDIFF_MAX ’ is enabled by default. Warnings controlled by the option can be disabled either by specifying byte-size of ‘ SIZE_MAX ’ or more or by -Wno-alloc-size-larger-than . See Declaring Attributes of Functions .

Disable -Walloc-size-larger-than= warnings. The option is equivalent to -Walloc-size-larger-than= ‘ SIZE_MAX ’ or larger.

This option warns on all uses of alloca in the source.

This option warns on calls to alloca with an integer argument whose value is either zero, or that is not bounded by a controlling predicate that limits its value to at most byte-size . It also warns for calls to alloca where the bound value is unknown. Arguments of non-integer types are considered unbounded even if they appear to be constrained to the expected range.

For example, a bounded case of alloca could be:

In the above example, passing -Walloca-larger-than=1000 would not issue a warning because the call to alloca is known to be at most 1000 bytes. However, if -Walloca-larger-than=500 were passed, the compiler would emit a warning.

Unbounded uses, on the other hand, are uses of alloca with no controlling predicate constraining its integer argument. For example:

If -Walloca-larger-than=500 were passed, the above would trigger a warning, but this time because of the lack of bounds checking.

Note, that even seemingly correct code involving signed integers could cause a warning:

In the above example, n could be negative, causing a larger than expected argument to be implicitly cast into the alloca call.

This option also warns when alloca is used in a loop.

-Walloca-larger-than= ‘ PTRDIFF_MAX ’ is enabled by default but is usually only effective when -ftree-vrp is active (default for -O2 and above).

See also -Wvla-larger-than= ‘ byte-size ’.

Disable -Walloca-larger-than= warnings. The option is equivalent to -Walloca-larger-than= ‘ SIZE_MAX ’ or larger.

Do warn about implicit conversions from arithmetic operations even when conversion of the operands to the same type cannot change their values. This affects warnings from -Wconversion , -Wfloat-conversion , and -Wsign-conversion .

Warn about out of bounds subscripts or offsets into arrays. This warning is enabled by -Wall . It is more effective when -ftree-vrp is active (the default for -O2 and above) but a subset of instances are issued even without optimization.

By default, the trailing array of a structure will be treated as a flexible array member by -Warray-bounds or -Warray-bounds= n if it is declared as either a flexible array member per C99 standard onwards (‘ [] ’), a GCC zero-length array extension (‘ [0] ’), or an one-element array (‘ [1] ’). As a result, out of bounds subscripts or offsets into zero-length arrays or one-element arrays are not warned by default.

You can add the option -fstrict-flex-arrays or -fstrict-flex-arrays= level to control how this option treat trailing array of a structure as a flexible array member:

when level <=1, no change to the default behavior.

when level =2, additional warnings will be issued for out of bounds subscripts or offsets into one-element arrays;

when level =3, in addition to level =2, additional warnings will be issued for out of bounds subscripts or offsets into zero-length arrays.

This is the default warning level of -Warray-bounds and is enabled by -Wall ; higher levels are not, and must be explicitly requested.

This warning level also warns about the intermediate results of pointer arithmetic that may yield out of bounds values. This warning level may give a larger number of false positives and is deactivated by default.

Warn about equality and relational comparisons between two operands of array type. This comparison was deprecated in C++20. For example:

-Warray-compare is enabled by -Wall .

Warn about redeclarations of functions involving parameters of array or pointer types of inconsistent kinds or forms, and enable the detection of out-of-bounds accesses to such parameters by warnings such as -Warray-bounds .

If the first function declaration uses the array form for a parameter declaration, the bound specified in the array is assumed to be the minimum number of elements expected to be provided in calls to the function and the maximum number of elements accessed by it. Failing to provide arguments of sufficient size or accessing more than the maximum number of elements may be diagnosed by warnings such as -Warray-bounds or -Wstringop-overflow . At level 1, the warning diagnoses inconsistencies involving array parameters declared using the T[static N] form.

For example, the warning triggers for the second declaration of f because the first one with the keyword static specifies that the array argument must have at least four elements, while the second allows an array of any size to be passed to f .

At level 2 the warning also triggers for redeclarations involving any other inconsistency in array or pointer argument forms denoting array sizes. Pointers and arrays of unspecified bound are considered equivalent and do not trigger a warning.

-Warray-parameter=2 is included in -Wall . The -Wvla-parameter option triggers warnings for similar inconsistencies involving Variable Length Array arguments.

The short form of the option -Warray-parameter is equivalent to -Warray-parameter=2 . The negative form -Wno-array-parameter is equivalent to -Warray-parameter=0 .

Warn about declarations using the alias and similar attributes whose target is incompatible with the type of the alias. See Declaring Attributes of Functions .

The default warning level of the -Wattribute-alias option diagnoses incompatibilities between the type of the alias declaration and that of its target. Such incompatibilities are typically indicative of bugs.

At this level -Wattribute-alias also diagnoses cases where the attributes of the alias declaration are more restrictive than the attributes applied to its target. These mismatches can potentially result in incorrect code generation. In other cases they may be benign and could be resolved simply by adding the missing attribute to the target. For comparison, see the -Wmissing-attributes option, which controls diagnostics when the alias declaration is less restrictive than the target, rather than more restrictive.

Attributes considered include alloc_align , alloc_size , cold , const , hot , leaf , malloc , nonnull , noreturn , nothrow , pure , returns_nonnull , and returns_twice .

-Wattribute-alias is equivalent to -Wattribute-alias=1 . This is the default. You can disable these warnings with either -Wno-attribute-alias or -Wattribute-alias=0 .

Warn about possibly misleading UTF-8 bidirectional control characters in comments, string literals, character constants, and identifiers. Such characters can change left-to-right writing direction into right-to-left (and vice versa), which can cause confusion between the logical order and visual order. This may be dangerous; for instance, it may seem that a piece of code is not commented out, whereas it in fact is.

There are three levels of warning supported by GCC. The default is -Wbidi-chars=unpaired , which warns about improperly terminated bidi contexts. -Wbidi-chars=none turns the warning off. -Wbidi-chars=any warns about any use of bidirectional control characters.

By default, this warning does not warn about UCNs. It is, however, possible to turn on such checking by using -Wbidi-chars=unpaired,ucn or -Wbidi-chars=any,ucn . Using -Wbidi-chars=ucn is valid, and is equivalent to -Wbidi-chars=unpaired,ucn , if no previous -Wbidi-chars=any was specified.

Warn about boolean expression compared with an integer value different from true / false . For instance, the following comparison is always false:

Warn about suspicious operations on expressions of a boolean type. For instance, bitwise negation of a boolean is very likely a bug in the program. For C, this warning also warns about incrementing or decrementing a boolean, which rarely makes sense. (In C++, decrementing a boolean is always invalid. Incrementing a boolean is invalid in C++17, and deprecated otherwise.)

Warn when an if-else has identical branches. This warning detects cases like

It doesn’t warn when both branches contain just a null statement. This warning also warn for conditional operators:

Warn about duplicated conditions in an if-else-if chain. For instance, warn for the following code:

Warn when the ‘ __builtin_frame_address ’ or ‘ __builtin_return_address ’ is called with an argument greater than 0. Such calls may return indeterminate values or crash the program. The warning is included in -Wall .

Do not warn if type qualifiers on pointers are being discarded. Typically, the compiler warns if a const char * variable is passed to a function that takes a char * parameter. This option can be used to suppress such a warning.

Do not warn if type qualifiers on arrays which are pointer targets are being discarded. Typically, the compiler warns if a const int (*)[] variable is passed to a function that takes a int (*)[] parameter. This option can be used to suppress such a warning.

Do not warn when there is a conversion between pointers that have incompatible types. This warning is for cases not covered by -Wno-pointer-sign , which warns for pointer argument passing or assignment with different signedness.

By default, in C99 and later dialects of C, GCC treats this issue as an error. The error can be downgraded to a warning using -fpermissive (along with certain other errors), or for this error alone, with -Wno-error=incompatible-pointer-types .

Do not warn about incompatible integer to pointer and pointer to integer conversions. This warning is about implicit conversions; for explicit conversions the warnings -Wno-int-to-pointer-cast and -Wno-pointer-to-int-cast may be used.

By default, in C99 and later dialects of C, GCC treats this issue as an error. The error can be downgraded to a warning using -fpermissive (along with certain other errors), or for this error alone, with -Wno-error=int-conversion .

Warn about accesses to elements of zero-length array members that might overlap other members of the same object. Declaring interior zero-length arrays is discouraged because accesses to them are undefined. See Arrays of Length Zero .

For example, the first two stores in function bad are diagnosed because the array elements overlap the subsequent members b and c . The third store is diagnosed by -Warray-bounds because it is beyond the bounds of the enclosing object.

Option -Wzero-length-bounds is enabled by -Warray-bounds .

Do not warn about compile-time integer division by zero. Floating-point division by zero is not warned about, as it can be a legitimate way of obtaining infinities and NaNs.

Print warning messages for constructs found in system header files. Warnings from system headers are normally suppressed, on the assumption that they usually do not indicate real problems and would only make the compiler output harder to read. Using this command-line option tells GCC to emit warnings from system headers as if they occurred in user code. However, note that using -Wall in conjunction with this option does not warn about unknown pragmas in system headers—for that, -Wunknown-pragmas must also be used.

Warn if a self-comparison always evaluates to true or false. This warning detects various mistakes such as:

This warning also warns about bitwise comparisons that always evaluate to true or false, for instance:

will always be false.

Warn about trampolines generated for pointers to nested functions. A trampoline is a small piece of data or code that is created at run time on the stack when the address of a nested function is taken, and is used to call the nested function indirectly. For some targets, it is made up of data only and thus requires no special treatment. But, for most targets, it is made up of code and thus requires the stack to be made executable in order for the program to work properly.

Warn if floating-point values are used in equality comparisons.

The idea behind this is that sometimes it is convenient (for the programmer) to consider floating-point values as approximations to infinitely precise real numbers. If you are doing this, then you need to compute (by analyzing the code, or in some other way) the maximum or likely maximum error that the computation introduces, and allow for it when performing comparisons (and when producing output, but that’s a different problem). In particular, instead of testing for equality, you should check to see whether the two values have ranges that overlap; and this is done with the relational operators, so equality comparisons are probably mistaken.

Warn about certain constructs that behave differently in traditional and ISO C. Also warn about ISO C constructs that have no traditional C equivalent, and/or problematic constructs that should be avoided.

  • Macro parameters that appear within string literals in the macro body. In traditional C macro replacement takes place within string literals, but in ISO C it does not.
  • In traditional C, some preprocessor directives did not exist. Traditional preprocessors only considered a line to be a directive if the ‘ # ’ appeared in column 1 on the line. Therefore -Wtraditional warns about directives that traditional C understands but ignores because the ‘ # ’ does not appear as the first character on the line. It also suggests you hide directives like #pragma not understood by traditional C by indenting them. Some traditional implementations do not recognize #elif , so this option suggests avoiding it altogether.
  • A function-like macro that appears without arguments.
  • The unary plus operator.
  • The ‘ U ’ integer constant suffix, or the ‘ F ’ or ‘ L ’ floating-point constant suffixes. (Traditional C does support the ‘ L ’ suffix on integer constants.) Note, these suffixes appear in macros defined in the system headers of most modern systems, e.g. the ‘ _MIN ’/‘ _MAX ’ macros in <limits.h> . Use of these macros in user code might normally lead to spurious warnings, however GCC’s integrated preprocessor has enough context to avoid warning in these cases.
  • A function declared external in one block and then used after the end of the block.
  • A switch statement has an operand of type long .
  • A non- static function declaration follows a static one. This construct is not accepted by some traditional C compilers.
  • The ISO type of an integer constant has a different width or signedness from its traditional type. This warning is only issued if the base of the constant is ten. I.e. hexadecimal or octal values, which typically represent bit patterns, are not warned about.
  • Usage of ISO string concatenation is detected.
  • Initialization of automatic aggregates.
  • Identifier conflicts with labels. Traditional C lacks a separate namespace for labels.
  • Initialization of unions. If the initializer is zero, the warning is omitted. This is done under the assumption that the zero initializer in user code appears conditioned on e.g. __STDC__ to avoid missing initializer warnings and relies on default initialization to zero in the traditional C case.
  • Conversions by prototypes between fixed/floating-point values and vice versa. The absence of these prototypes when compiling with traditional C causes serious problems. This is a subset of the possible conversion warnings; for the full set use -Wtraditional-conversion .
  • Use of ISO C style function definitions. This warning intentionally is not issued for prototype declarations or variadic functions because these ISO C features appear in your code when using libiberty’s traditional C compatibility macros, PARAMS and VPARAMS . This warning is also bypassed for nested functions because that feature is already a GCC extension and thus not relevant to traditional C compatibility.

Warn if a prototype causes a type conversion that is different from what would happen to the same argument in the absence of a prototype. This includes conversions of fixed point to floating and vice versa, and conversions changing the width or signedness of a fixed-point argument except when the same as the default promotion.

Warn when a declaration is found after a statement in a block. This construct, known from C++, was introduced with ISO C99 and is by default allowed in GCC. It is not supported by ISO C90. See Mixed Declarations, Labels and Code .

Warn whenever a local variable or type declaration shadows another variable, parameter, type, class member (in C++), or instance variable (in Objective-C) or whenever a built-in function is shadowed. Note that in C++, the compiler warns if a local variable shadows an explicit typedef, but not if it shadows a struct/class/enum. If this warning is enabled, it includes also all instances of local shadowing. This means that -Wno-shadow=local and -Wno-shadow=compatible-local are ignored when -Wshadow is used. Same as -Wshadow=global .

Do not warn whenever a local variable shadows an instance variable in an Objective-C method.

Warn for any shadowing. Same as -Wshadow .

Warn when a local variable shadows another local variable or parameter.

Warn when a local variable shadows another local variable or parameter whose type is compatible with that of the shadowing variable. In C++, type compatibility here means the type of the shadowing variable can be converted to that of the shadowed variable. The creation of this flag (in addition to -Wshadow=local ) is based on the idea that when a local variable shadows another one of incompatible type, it is most likely intentional, not a bug or typo, as shown in the following example:

Since the two variable i in the example above have incompatible types, enabling only -Wshadow=compatible-local does not emit a warning. Because their types are incompatible, if a programmer accidentally uses one in place of the other, type checking is expected to catch that and emit an error or warning. Use of this flag instead of -Wshadow=local can possibly reduce the number of warnings triggered by intentional shadowing. Note that this also means that shadowing const char *i by char *i does not emit a warning.

This warning is also enabled by -Wshadow=local .

Warn whenever an object is defined whose size exceeds byte-size . -Wlarger-than= ‘ PTRDIFF_MAX ’ is enabled by default. Warnings controlled by the option can be disabled either by specifying byte-size of ‘ SIZE_MAX ’ or more or by -Wno-larger-than .

Also warn for calls to bounded functions such as memchr or strnlen that specify a bound greater than the largest possible object, which is ‘ PTRDIFF_MAX ’ bytes by default. These warnings can only be disabled by -Wno-larger-than .

Disable -Wlarger-than= warnings. The option is equivalent to -Wlarger-than= ‘ SIZE_MAX ’ or larger.

Warn if the size of a function frame exceeds byte-size . The computation done to determine the stack frame size is approximate and not conservative. The actual requirements may be somewhat greater than byte-size even if you do not get a warning. In addition, any space allocated via alloca , variable-length arrays, or related constructs is not included by the compiler when determining whether or not to issue a warning. -Wframe-larger-than= ‘ PTRDIFF_MAX ’ is enabled by default. Warnings controlled by the option can be disabled either by specifying byte-size of ‘ SIZE_MAX ’ or more or by -Wno-frame-larger-than .

Disable -Wframe-larger-than= warnings. The option is equivalent to -Wframe-larger-than= ‘ SIZE_MAX ’ or larger.

Warn when attempting to deallocate an object that was either not allocated on the heap, or by using a pointer that was not returned from a prior call to the corresponding allocation function. For example, because the call to stpcpy returns a pointer to the terminating nul character and not to the beginning of the object, the call to free below is diagnosed.

-Wfree-nonheap-object is included in -Wall .

Warn if the stack usage of a function might exceed byte-size . The computation done to determine the stack usage is conservative. Any space allocated via alloca , variable-length arrays, or related constructs is included by the compiler when determining whether or not to issue a warning.

The message is in keeping with the output of -fstack-usage .

  • If the stack usage is fully static but exceeds the specified amount, it’s: warning: stack usage is 1120 bytes
  • If the stack usage is (partly) dynamic but bounded, it’s: warning: stack usage might be 1648 bytes
  • If the stack usage is (partly) dynamic and not bounded, it’s: warning: stack usage might be unbounded

-Wstack-usage= ‘ PTRDIFF_MAX ’ is enabled by default. Warnings controlled by the option can be disabled either by specifying byte-size of ‘ SIZE_MAX ’ or more or by -Wno-stack-usage .

Disable -Wstack-usage= warnings. The option is equivalent to -Wstack-usage= ‘ SIZE_MAX ’ or larger.

Warn if the loop cannot be optimized because the compiler cannot assume anything on the bounds of the loop indices. With -funsafe-loop-optimizations warn if the compiler makes such assumptions.

When used in combination with -Wformat and -pedantic without GNU extensions, this option disables the warnings about non-ISO printf / scanf format width specifiers I32 , I64 , and I used on Windows targets, which depend on the MS runtime.

Warn about anything that depends on the “size of” a function type or of void . GNU C assigns these types a size of 1, for convenience in calculations with void * pointers and pointers to functions. In C++, warn also when an arithmetic operation involves NULL . This warning is also enabled by -Wpedantic .

Do not warn if a pointer is compared with a zero character constant. This usually means that the pointer was meant to be dereferenced. For example:

Note that the code above is invalid in C++11.

This warning is enabled by default.

Disable warnings about unsupported features in ThreadSanitizer.

ThreadSanitizer does not support std::atomic_thread_fence and can report false positives.

Warn if a comparison is always true or always false due to the limited range of the data type, but do not warn for constant expressions. For example, warn if an unsigned variable is compared against zero with < or >= . This warning is also enabled by -Wextra .

Warn for calls to standard functions that compute the absolute value of an argument when a more appropriate standard function is available. For example, calling abs(3.14) triggers the warning because the appropriate function to call to compute the absolute value of a double argument is fabs . The option also triggers warnings when the argument in a call to such a function has an unsigned type. This warning can be suppressed with an explicit type cast and it is also enabled by -Wextra .

Warn whenever a comment-start sequence ‘ /* ’ appears in a ‘ /* ’ comment, or whenever a backslash-newline appears in a ‘ // ’ comment. This warning is enabled by -Wall .

Warn if any trigraphs are encountered that might change the meaning of the program. Trigraphs within comments are not warned about, except those that would form escaped newlines.

This option is implied by -Wall . If -Wall is not given, this option is still enabled unless trigraphs are enabled. To get trigraph conversion without warnings, but get the other -Wall warnings, use ‘ -trigraphs -Wall -Wno-trigraphs ’.

Warn if an undefined identifier is evaluated in an #if directive. Such identifiers are replaced with zero.

Warn whenever ‘ defined ’ is encountered in the expansion of a macro (including the case where the macro is expanded by an ‘ #if ’ directive). Such usage is not portable. This warning is also enabled by -Wpedantic and -Wextra .

Warn about macros defined in the main file that are unused. A macro is used if it is expanded or tested for existence at least once. The preprocessor also warns if the macro has not been used at the time it is redefined or undefined.

Built-in macros, macros defined on the command line, and macros defined in include files are not warned about.

Note: If a macro is actually used, but only used in skipped conditional blocks, then the preprocessor reports it as unused. To avoid the warning in such a case, you might improve the scope of the macro’s definition by, for example, moving it into the first skipped block. Alternatively, you could provide a dummy use with something like:

Do not warn whenever an #else or an #endif are followed by text. This sometimes happens in older programs with code of the form

The second and third FOO should be in comments. This warning is on by default.

Warn when a function call is cast to a non-matching type. For example, warn if a call to a function returning an integer type is cast to a pointer type.

Warn about features not present in ISO C90, but present in ISO C99. For instance, warn about use of variable length arrays, long long type, bool type, compound literals, designated initializers, and so on. This option is independent of the standards mode. Warnings are disabled in the expression that follows __extension__ .

Warn about features not present in ISO C99, but present in ISO C11. For instance, warn about use of anonymous structures and unions, _Atomic type qualifier, _Thread_local storage-class specifier, _Alignas specifier, Alignof operator, _Generic keyword, and so on. This option is independent of the standards mode. Warnings are disabled in the expression that follows __extension__ .

Warn about features not present in ISO C11, but present in ISO C23. For instance, warn about omitting the string in _Static_assert , use of ‘ [[]] ’ syntax for attributes, use of decimal floating-point types, and so on. This option is independent of the standards mode. Warnings are disabled in the expression that follows __extension__ . The name -Wc11-c2x-compat is deprecated.

When not compiling in C23 mode, these warnings are upgraded to errors by -pedantic-errors .

Warn about ISO C constructs that are outside of the common subset of ISO C and ISO C++, e.g. request for implicit conversion from void * to a pointer to non- void type.

Warn about C++ constructs whose meaning differs between ISO C++ 1998 and ISO C++ 2011, e.g., identifiers in ISO C++ 1998 that are keywords in ISO C++ 2011. This warning turns on -Wnarrowing and is enabled by -Wall .

Warn about C++ constructs whose meaning differs between ISO C++ 2011 and ISO C++ 2014. This warning is enabled by -Wall .

Warn about C++ constructs whose meaning differs between ISO C++ 2014 and ISO C++ 2017. This warning is enabled by -Wall .

Warn about C++ constructs whose meaning differs between ISO C++ 2017 and ISO C++ 2020. This warning is enabled by -Wall .

Do not warn about C++11 constructs in code being compiled using an older C++ standard. Even without this option, some C++11 constructs will only be diagnosed if -Wpedantic is used.

Do not warn about C++14 constructs in code being compiled using an older C++ standard. Even without this option, some C++14 constructs will only be diagnosed if -Wpedantic is used.

Do not warn about C++17 constructs in code being compiled using an older C++ standard. Even without this option, some C++17 constructs will only be diagnosed if -Wpedantic is used.

Do not warn about C++20 constructs in code being compiled using an older C++ standard. Even without this option, some C++20 constructs will only be diagnosed if -Wpedantic is used.

Do not warn about C++23 constructs in code being compiled using an older C++ standard. Even without this option, some C++23 constructs will only be diagnosed if -Wpedantic is used.

Do not warn about C++26 constructs in code being compiled using an older C++ standard. Even without this option, some C++26 constructs will only be diagnosed if -Wpedantic is used.

Warn whenever a pointer is cast so as to remove a type qualifier from the target type. For example, warn if a const char * is cast to an ordinary char * .

Also warn when making a cast that introduces a type qualifier in an unsafe way. For example, casting char ** to const char ** is unsafe, as in this example:

Warn whenever a pointer is cast such that the required alignment of the target is increased. For example, warn if a char * is cast to an int * on machines where integers can only be accessed at two- or four-byte boundaries.

Warn whenever a pointer is cast such that the required alignment of the target is increased. For example, warn if a char * is cast to an int * regardless of the target machine.

Warn when a function pointer is cast to an incompatible function pointer. In a cast involving function types with a variable argument list only the types of initial arguments that are provided are considered. Any parameter of pointer-type matches any other pointer-type. Any benign differences in integral types are ignored, like int vs. long on ILP32 targets. Likewise type qualifiers are ignored. The function type void (*) (void) is special and matches everything, which can be used to suppress this warning. In a cast involving pointer to member types this warning warns whenever the type cast is changing the pointer to member type. This warning is enabled by -Wextra .

Warn when a cast to reference type does not involve a user-defined conversion that the programmer might expect to be called.

When compiling C, give string constants the type const char[ length ] so that copying the address of one into a non- const char * pointer produces a warning. These warnings help you find at compile time code that can try to write into a string constant, but only if you have been very careful about using const in declarations and prototypes. Otherwise, it is just a nuisance. This is why we did not make -Wall request these warnings.

When compiling C++, warn about the deprecated conversion from string literals to char * . This warning is enabled by default for C++ programs.

This warning is upgraded to an error by -pedantic-errors in C++11 mode or later.

Warn for variables that might be changed by longjmp or vfork . This warning is also enabled by -Wextra .

By default, language front ends complain when a command-line option is valid, but not applicable to that front end. This may be disabled with -Wno-complain-wrong-lang , which is mostly useful when invoking a single compiler driver for multiple source files written in different languages, for example:

The driver g++ invokes the C++ front end to compile a.cc and the Fortran front end to compile b.f90 . The latter front end diagnoses ‘ f951: Warning: command-line option '-fno-rtti' is valid for C++/D/ObjC++ but not for Fortran ’, which may be disabled with -Wno-complain-wrong-lang .

Warn if pointers of distinct types are compared without a cast. This warning is enabled by default.

Warn for implicit conversions that may alter a value. This includes conversions between real and integer, like abs (x) when x is double ; conversions between signed and unsigned, like unsigned ui = -1 ; and conversions to smaller types, like sqrtf (M_PI) . Do not warn for explicit casts like abs ((int) x) and ui = (unsigned) -1 , or if the value is not changed by the conversion like in abs (2.0) . Warnings about conversions between signed and unsigned integers can be disabled by using -Wno-sign-conversion .

For C++, also warn for confusing overload resolution for user-defined conversions; and conversions that never use a type conversion operator: conversions to void , the same type, a base class or a reference to them. Warnings about conversions between signed and unsigned integers are disabled by default in C++ unless -Wsign-conversion is explicitly enabled.

Warnings about conversion from arithmetic on a small type back to that type are only given with -Warith-conversion .

Warn about constructions where there may be confusion to which if statement an else branch belongs. Here is an example of such a case:

In C/C++, every else branch belongs to the innermost possible if statement, which in this example is if (b) . This is often not what the programmer expected, as illustrated in the above example by indentation the programmer chose. When there is the potential for this confusion, GCC issues a warning when this flag is specified. To eliminate the warning, add explicit braces around the innermost if statement so there is no way the else can belong to the enclosing if . The resulting code looks like this:

This warning is enabled by -Wparentheses .

Warn about uses of pointers (or C++ references) to objects with automatic storage duration after their lifetime has ended. This includes local variables declared in nested blocks, compound literals and other unnamed temporary objects. In addition, warn about storing the address of such objects in escaped pointers. The warning is enabled at all optimization levels but may yield different results with optimization than without.

At level 1, the warning diagnoses only unconditional uses of dangling pointers.

At level 2, in addition to unconditional uses the warning also diagnoses conditional uses of dangling pointers.

The short form -Wdangling-pointer is equivalent to -Wdangling-pointer=2 , while -Wno-dangling-pointer and -Wdangling-pointer=0 have the same effect of disabling the warnings. -Wdangling-pointer=2 is included in -Wall .

This example triggers the warning at level 1; the address of the unnamed temporary is unconditionally referenced outside of its scope.

In the following function the store of the address of the local variable x in the escaped pointer *p triggers the warning at level 1.

In this example, the array a is out of scope when the pointer s is used. Since the code that sets s is conditional, the warning triggers at level 2.

Warn when macros __TIME__ , __DATE__ or __TIMESTAMP__ are encountered as they might prevent bit-wise-identical reproducible compilations.

Warn if an empty body occurs in an if , else or do while statement. This warning is also enabled by -Wextra .

Do not warn about stray tokens after #else and #endif .

Warn about a comparison between values of different enumerated types. In C++ enumerated type mismatches in conditional expressions are also diagnosed and the warning is enabled by default. In C this warning is enabled by -Wall .

Warn when a value of enumerated type is implicitly converted to a different enumerated type. This warning is enabled by -Wextra in C.

Warn about mismatches between an enumerated type and an integer type in declarations. For example:

In C, an enumerated type is compatible with char , a signed integer type, or an unsigned integer type. However, since the choice of the underlying type of an enumerated type is implementation-defined, such mismatches may cause portability issues. In C++, such mismatches are an error. In C, this warning is enabled by -Wall and -Wc++-compat .

Warn if a goto statement or a switch statement jumps forward across the initialization of a variable, or jumps backward to a label after the variable has been initialized. This only warns about variables that are initialized when they are declared. This warning is only supported for C and Objective-C; in C++ this sort of branch is an error in any case.

-Wjump-misses-init is included in -Wc++-compat . It can be disabled with the -Wno-jump-misses-init option.

Warn when a comparison between signed and unsigned values could produce an incorrect result when the signed value is converted to unsigned. In C++, this warning is also enabled by -Wall . In C, it is also enabled by -Wextra .

Warn for implicit conversions that may change the sign of an integer value, like assigning a signed integer expression to an unsigned integer variable. An explicit cast silences the warning. In C, this option is enabled also by -Wconversion .

Warn when a structure containing a C99 flexible array member as the last field is not at the end of another structure. This warning warns e.g. about

Warn for implicit conversions that reduce the precision of a real value. This includes conversions from real to integer, and from higher precision real to lower precision real values. This option is also enabled by -Wconversion .

Do not warn on suspicious constructs involving reverse scalar storage order.

Warn about divisions of two sizeof operators when the first one is applied to an array and the divisor does not equal the size of the array element. In such a case, the computation will not yield the number of elements in the array, which is likely what the user intended. This warning warns e.g. about

Warn for suspicious divisions of two sizeof expressions that divide the pointer size by the element size, which is the usual way to compute the array size but won’t work out correctly with pointers. This warning warns e.g. about sizeof (ptr) / sizeof (ptr[0]) if ptr is not an array, but a pointer. This warning is enabled by -Wall .

Warn for suspicious length parameters to certain string and memory built-in functions if the argument uses sizeof . This warning triggers for example for memset (ptr, 0, sizeof (ptr)); if ptr is not an array, but a pointer, and suggests a possible fix, or about memcpy (&foo, ptr, sizeof (&foo)); . -Wsizeof-pointer-memaccess also warns about calls to bounded string copy functions like strncat or strncpy that specify as the bound a sizeof expression of the source array. For example, in the following function the call to strncat specifies the size of the source string as the bound. That is almost certainly a mistake and so the call is diagnosed.

The -Wsizeof-pointer-memaccess option is enabled by -Wall .

Do not warn when the sizeof operator is applied to a parameter that is declared as an array in a function definition. This warning is enabled by default for C and C++ programs.

Warn for suspicious calls to the memset built-in function, if the first argument references an array, and the third argument is a number equal to the number of elements, but not equal to the size of the array in memory. This indicates that the user has omitted a multiplication by the element size. This warning is enabled by -Wall .

Warn for suspicious calls to the memset built-in function where the second argument is not zero and the third argument is zero. For example, the call memset (buf, sizeof buf, 0) is diagnosed because memset (buf, 0, sizeof buf) was meant instead. The diagnostic is only emitted if the third argument is a literal zero. Otherwise, if it is an expression that is folded to zero, or a cast of zero to some type, it is far less likely that the arguments have been mistakenly transposed and no warning is emitted. This warning is enabled by -Wall .

Warn about suspicious uses of address expressions. These include comparing the address of a function or a declared object to the null pointer constant such as in

comparisons of a pointer to a string literal, such as in

and tests of the results of pointer addition or subtraction for equality to null, such as in

Such uses typically indicate a programmer error: the address of most functions and objects necessarily evaluates to true (the exception are weak symbols), so their use in a conditional might indicate missing parentheses in a function call or a missing dereference in an array expression. The subset of the warning for object pointers can be suppressed by casting the pointer operand to an integer type such as intptr_t or uintptr_t . Comparisons against string literals result in unspecified behavior and are not portable, and suggest the intent was to call strcmp . The warning is suppressed if the suspicious expression is the result of macro expansion. -Waddress warning is enabled by -Wall .

Do not warn when the address of packed member of struct or union is taken, which usually results in an unaligned pointer value. This is enabled by default.

Warn about suspicious uses of logical operators in expressions. This includes using logical operators in contexts where a bit-wise operator is likely to be expected. Also warns when the operands of a logical operator are the same:

Warn about logical not used on the left hand side operand of a comparison. This option does not warn if the right operand is considered to be a boolean expression. Its purpose is to detect suspicious code like the following:

It is possible to suppress the warning by wrapping the LHS into parentheses:

Warn if any functions that return structures or unions are defined or called. (In languages where you can return an array, this also elicits a warning.)

Warn if in a loop with constant number of iterations the compiler detects undefined behavior in some statement during one or more of the iterations.

Do not warn if an unexpected __attribute__ is used, such as unrecognized attributes, function attributes applied to variables, etc. This does not stop errors for incorrect use of supported attributes.

Warnings about ill-formed uses of standard attributes are upgraded to errors by -pedantic-errors .

Additionally, using -Wno-attributes= , it is possible to suppress warnings about unknown scoped attributes (in C++11 and C23). For example, -Wno-attributes=vendor::attr disables warning about the following declaration:

It is also possible to disable warning about all attributes in a namespace using -Wno-attributes=vendor:: which prevents warning about both of these declarations:

Note that -Wno-attributes= does not imply -Wno-attributes .

Warn if a built-in function is declared with an incompatible signature or as a non-function, or when a built-in function declared with a type that does not include a prototype is called with arguments whose promoted types do not match those expected by the function. When -Wextra is specified, also warn when a built-in function that takes arguments is declared without a prototype. The -Wbuiltin-declaration-mismatch warning is enabled by default. To avoid the warning include the appropriate header to bring the prototypes of built-in functions into scope.

For example, the call to memset below is diagnosed by the warning because the function expects a value of type size_t as its argument but the type of 32 is int . With -Wextra , the declaration of the function is diagnosed as well.

Do not warn if certain built-in macros are redefined. This suppresses warnings for redefinition of __TIMESTAMP__ , __TIME__ , __DATE__ , __FILE__ , and __BASE_FILE__ .

Warn if a function is declared or defined without specifying the argument types. (An old-style function definition is permitted without a warning if preceded by a declaration that specifies the argument types.)

Warn for obsolescent usages, according to the C Standard, in a declaration. For example, warn if storage-class specifiers like static are not the first things in a declaration. This warning is also enabled by -Wextra .

Warn if an old-style function definition is used. A warning is given even if there is a previous prototype. A definition using ‘ () ’ is not considered an old-style definition in C23 mode, because it is equivalent to ‘ (void) ’ in that case, but is considered an old-style definition for older standards.

A function parameter is declared without a type specifier in K&R-style functions:

Do not warn if a function declaration contains a parameter name without a type. Such function declarations do not provide a function prototype and prevent most type checking in function calls.

This warning is enabled by default. In C99 and later dialects of C, it is treated as an error. The error can be downgraded to a warning using -fpermissive (along with certain other errors), or for this error alone, with -Wno-error=declaration-missing-parameter-type .

Warn if a global function is defined without a previous prototype declaration. This warning is issued even if the definition itself provides a prototype. Use this option to detect global functions that do not have a matching prototype declaration in a header file. This option is not valid for C++ because all function declarations provide prototypes and a non-matching declaration declares an overload rather than conflict with an earlier declaration. Use -Wmissing-declarations to detect missing declarations in C++.

Warn if a global variable is defined without a previous declaration. Use this option to detect global variables that do not have a matching extern declaration in a header file.

Warn if a global function is defined without a previous declaration. Do so even if the definition itself provides a prototype. Use this option to detect global functions that are not declared in header files. In C, no warnings are issued for functions with previous non-prototype declarations; use -Wmissing-prototypes to detect missing prototypes. In C++, no warnings are issued for function templates, or for inline functions, or for functions in anonymous namespaces.

Warn if a structure’s initializer has some fields missing. For example, the following code causes such a warning, because x.h is implicitly zero:

In C this option does not warn about designated initializers, so the following modification does not trigger a warning:

In C this option does not warn about the universal zero initializer ‘ { 0 } ’:

Likewise, in C++ this option does not warn about the empty { } initializer, for example:

This warning is included in -Wextra . To get other -Wextra warnings without this one, use -Wextra -Wno-missing-field-initializers .

By default, the compiler warns about a concept-id appearing as a C++20 simple-requirement:

Here ‘ satisfied ’ will be true if ‘ C<T> ’ is a valid expression, which it is for all T. Presumably the user meant to write

so ‘ satisfied ’ is only true if concept ‘ C ’ is satisfied for type ‘ T ’.

This warning can be disabled with -Wno-missing-requires .

The member access tokens ., -> and :: must be followed by the template keyword if the parent object is dependent and the member being named is a template.

In rare cases it is possible to get false positives. To silence this, wrap the expression in parentheses. For example, the following is treated as a template, even where m and N are integers:

This warning can be disabled with -Wno-missing-template-keyword .

Do not warn if a multicharacter constant (‘ 'FOOF' ’) is used. Usually they indicate a typo in the user’s code, as they have implementation-defined values, and should not be used in portable code.

In ISO C and ISO C++, two identifiers are different if they are different sequences of characters. However, sometimes when characters outside the basic ASCII character set are used, you can have two different character sequences that look the same. To avoid confusion, the ISO 10646 standard sets out some normalization rules which when applied ensure that two sequences that look the same are turned into the same sequence. GCC can warn you if you are using identifiers that have not been normalized; this option controls that warning.

There are four levels of warning supported by GCC. The default is -Wnormalized=nfc , which warns about any identifier that is not in the ISO 10646 “C” normalized form, NFC . NFC is the recommended form for most uses. It is equivalent to -Wnormalized .

Unfortunately, there are some characters allowed in identifiers by ISO C and ISO C++ that, when turned into NFC, are not allowed in identifiers. That is, there’s no way to use these symbols in portable ISO C or C++ and have all your identifiers in NFC. -Wnormalized=id suppresses the warning for these characters. It is hoped that future versions of the standards involved will correct this, which is why this option is not the default.

You can switch the warning off for all characters by writing -Wnormalized=none or -Wno-normalized . You should only do this if you are using some other normalization scheme (like “D”), because otherwise you can easily create bugs that are literally impossible to see.

Some characters in ISO 10646 have distinct meanings but look identical in some fonts or display methodologies, especially once formatting has been applied. For instance \u207F , “SUPERSCRIPT LATIN SMALL LETTER N”, displays just like a regular n that has been placed in a superscript. ISO 10646 defines the NFKC normalization scheme to convert all these into a standard form as well, and GCC warns if your code is not in NFKC if you use -Wnormalized=nfkc . This warning is comparable to warning about every identifier that contains the letter O because it might be confused with the digit 0, and so is not the default, but may be useful as a local coding convention if the programming environment cannot be fixed to display these characters distinctly.

Do not warn about usage of functions (see Declaring Attributes of Functions ) declared with warning attribute. By default, this warning is enabled. -Wno-attribute-warning can be used to disable the warning or -Wno-error=attribute-warning can be used to disable the error when compiled with -Werror flag.

Do not warn about usage of deprecated features. See Deprecated Features .

Do not warn about uses of functions (see Declaring Attributes of Functions ), variables (see Specifying Attributes of Variables ), and types (see Specifying Attributes of Types ) marked as deprecated by using the deprecated attribute.

Do not warn about compile-time overflow in constant expressions.

Warn about One Definition Rule violations during link-time optimization. Enabled by default.

Warn about potentially suboptimal choices related to OpenACC parallelism.

Warn about suspicious OpenMP code.

Warn if the vectorizer cost model overrides the OpenMP simd directive set by user. The -fsimd-cost-model=unlimited option can be used to relax the cost model.

Warn if an initialized field without side effects is overridden when using designated initializers (see Designated Initializers ).

This warning is included in -Wextra . To get other -Wextra warnings without this one, use -Wextra -Wno-override-init .

Do not warn if an initialized field with side effects is overridden when using designated initializers (see Designated Initializers ). This warning is enabled by default.

Warn if a structure is given the packed attribute, but the packed attribute has no effect on the layout or size of the structure. Such structures may be mis-aligned for little benefit. For instance, in this code, the variable f.x in struct bar is misaligned even though struct bar does not itself have the packed attribute:

The 4.1, 4.2 and 4.3 series of GCC ignore the packed attribute on bit-fields of type char . This was fixed in GCC 4.4 but the change can lead to differences in the structure layout. GCC informs you when the offset of such a field has changed in GCC 4.4. For example there is no longer a 4-bit padding between field a and b in this structure:

This warning is enabled by default. Use -Wno-packed-bitfield-compat to disable this warning.

Warn if a structure field with explicitly specified alignment in a packed struct or union is misaligned. For example, a warning will be issued on struct S , like, warning: alignment 1 of 'struct S' is less than 8 , in this code:

Warn if padding is included in a structure, either to align an element of the structure or to align the whole structure. Sometimes when this happens it is possible to rearrange the fields of the structure to reduce the padding and so make the structure smaller.

Warn if anything is declared more than once in the same scope, even in cases where multiple declaration is valid and changes nothing.

Warn when an object referenced by a restrict -qualified parameter (or, in C++, a __restrict -qualified parameter) is aliased by another argument, or when copies between such objects overlap. For example, the call to the strcpy function below attempts to truncate the string by replacing its initial characters with the last four. However, because the call writes the terminating NUL into a[4] , the copies overlap and the call is diagnosed.

The -Wrestrict option detects some instances of simple overlap even without optimization but works best at -O2 and above. It is included in -Wall .

Warn if an extern declaration is encountered within a function.

Warn if a function that is declared as inline cannot be inlined. Even with this option, the compiler does not warn about failures to inline functions declared in system headers.

The compiler uses a variety of heuristics to determine whether or not to inline a function. For example, the compiler takes into account the size of the function being inlined and the amount of inlining that has already been done in the current function. Therefore, seemingly insignificant changes in the source program can cause the warnings produced by -Winline to appear or disappear.

Warn about use of C++17 std::hardware_destructive_interference_size without specifying its value with --param destructive-interference-size . Also warn about questionable values for that option.

This variable is intended to be used for controlling class layout, to avoid false sharing in concurrent code:

Here ‘ one ’ and ‘ two ’ are intended to be far enough apart that stores to one won’t require accesses to the other to reload the cache line.

By default, --param destructive-interference-size and --param constructive-interference-size are set based on the current -mtune option, typically to the L1 cache line size for the particular target CPU, sometimes to a range if tuning for a generic target. So all translation units that depend on ABI compatibility for the use of these variables must be compiled with the same -mtune (or -mcpu ).

If ABI stability is important, such as if the use is in a header for a library, you should probably not use the hardware interference size variables at all. Alternatively, you can force a particular value with --param .

If you are confident that your use of the variable does not affect ABI outside a single build of your project, you can turn off the warning with -Wno-interference-size .

Warn for suspicious use of integer values where boolean values are expected, such as conditional expressions (?:) using non-boolean integer constants in boolean context, like if (a <= b ? 2 : 3) . Or left shifting of signed integers in boolean context, like for (a = 0; 1 << a; a++); . Likewise for all kinds of multiplications regardless of the data type. This warning is enabled by -Wall .

Suppress warnings from casts to pointer type of an integer of a different size. In C++, casting to a pointer type of smaller size is an error. Wint-to-pointer-cast is enabled by default.

Suppress warnings from casts from a pointer to an integer type of a different size.

Warn if a precompiled header (see Using Precompiled Headers ) is found in the search path but cannot be used.

Warn if an invalid UTF-8 character is found. This warning is on by default for C++23 if -finput-charset=UTF-8 is used and turned into error with -pedantic-errors .

Don’t diagnose invalid forms of delimited or named escape sequences which are treated as separate tokens. Wunicode is enabled by default.

Warn if long long type is used. This is enabled by either -Wpedantic or -Wtraditional in ISO C90 and C++98 modes. To inhibit the warning messages, use -Wno-long-long .

Warn if variadic macros are used in ISO C90 mode, or if the GNU alternate syntax is used in ISO C99 mode. This is enabled by either -Wpedantic or -Wtraditional . To inhibit the warning messages, use -Wno-variadic-macros .

Do not warn upon questionable usage of the macros used to handle variable arguments like va_start . These warnings are enabled by default.

Warn if vector operation is not implemented via SIMD capabilities of the architecture. Mainly useful for the performance tuning. Vector operation can be implemented piecewise , which means that the scalar operation is performed on every vector element; in parallel , which means that the vector operation is implemented using scalars of wider type, which normally is more performance efficient; and as a single scalar , which means that vector fits into a scalar type.

Warn if a variable-length array is used in the code. -Wno-vla prevents the -Wpedantic warning of the variable-length array.

If this option is used, the compiler warns for declarations of variable-length arrays whose size is either unbounded, or bounded by an argument that allows the array size to exceed byte-size bytes. This is similar to how -Walloca-larger-than= byte-size works, but with variable-length arrays.

Note that GCC may optimize small variable-length arrays of a known value into plain arrays, so this warning may not get triggered for such arrays.

-Wvla-larger-than= ‘ PTRDIFF_MAX ’ is enabled by default but is typically only effective when -ftree-vrp is active (default for -O2 and above).

See also -Walloca-larger-than= byte-size .

Disable -Wvla-larger-than= warnings. The option is equivalent to -Wvla-larger-than= ‘ SIZE_MAX ’ or larger.

Warn about redeclarations of functions involving arguments of Variable Length Array types of inconsistent kinds or forms, and enable the detection of out-of-bounds accesses to such parameters by warnings such as -Warray-bounds .

If the first function declaration uses the VLA form the bound specified in the array is assumed to be the minimum number of elements expected to be provided in calls to the function and the maximum number of elements accessed by it. Failing to provide arguments of sufficient size or accessing more than the maximum number of elements may be diagnosed.

For example, the warning triggers for the following redeclarations because the first one allows an array of any size to be passed to f while the second one specifies that the array argument must have at least n elements. In addition, calling f with the associated VLA bound parameter in excess of the actual VLA bound triggers a warning as well.

-Wvla-parameter is included in -Wall . The -Warray-parameter option triggers warnings for similar problems involving ordinary array arguments.

Warn if a register variable is declared volatile. The volatile modifier does not inhibit all optimizations that may eliminate reads and/or writes to register variables. This warning is enabled by -Wall .

Disable warnings about uses of ^ , the exclusive or operator, where it appears the code meant exponentiation. Specifically, the warning occurs when the left-hand side is the decimal constant 2 or 10 and the right-hand side is also a decimal constant.

In C and C++, ^ means exclusive or, whereas in some other languages (e.g. TeX and some versions of BASIC) it means exponentiation.

This warning can be silenced by converting one of the operands to hexadecimal as well as by compiling with -Wno-xor-used-as-pow .

Warn if a requested optimization pass is disabled. This warning does not generally indicate that there is anything wrong with your code; it merely indicates that GCC’s optimizers are unable to handle the code effectively. Often, the problem is that your code is too big or too complex; GCC refuses to optimize programs when the optimization itself is likely to take inordinate amounts of time.

Warn for pointer argument passing or assignment with different signedness. This option is only supported for C and Objective-C. It is implied by -Wall and by -Wpedantic , which can be disabled with -Wno-pointer-sign .

This option is only active when -fstack-protector is active. It warns about functions that are not protected against stack smashing.

Warn about string constants that are longer than the “minimum maximum” length specified in the C standard. Modern compilers generally allow string constants that are much longer than the standard’s minimum limit, but very portable programs should avoid using longer strings.

The limit applies after string constant concatenation, and does not count the trailing NUL. In C90, the limit was 509 characters; in C99, it was raised to 4095. C++98 does not specify a normative minimum maximum, so we do not diagnose overlength strings in C++.

This option is implied by -Wpedantic , and can be disabled with -Wno-overlength-strings .

Issue a warning for any floating constant that does not have a suffix. When used together with -Wsystem-headers it warns about such constants in system header files. This can be useful when preparing code to use with the FLOAT_CONST_DECIMAL64 pragma from the decimal floating-point extension to C99.

During the link-time optimization, do not warn about type mismatches in global declarations from different compilation units. Requires -flto to be enabled. Enabled by default.

Suppress warnings when a positional initializer is used to initialize a structure that has been marked with the designated_init attribute.

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

What alternatives are there for C/C++ assignment operator (=) and equality operators (==) syntax?

C/C++ use = for assignment and == for equality comparision. For example, a snippet in C++ can be like this:

But this can lead to unwanted bugs when programmers accidentally make a typo. Consider this example:

This is a (very) common typo in C/C++, partly because the two operators are so similar.

So what are the alternatives?

  • language-design

kaya3's user avatar

  • 4 $\begingroup$ Whatever syntax you choose for these, you can prevent this exact mistake by not having assignment expressions at all. nuclear_code = 1234; can be a statement without nuclear_code = 1234 needing to be allowed as an expression; Python did this before eventually relenting and adding the assignment operator := . Another issue that works against C in this regard is the coercion to boolean; in Java, if(nuclear_code = 1234) would be a type error because the condition must be a boolean , not an int . $\endgroup$ –  kaya3 May 21, 2023 at 10:27
  • $\begingroup$ @kaya3 while that is true, the C/C++ way of doing it is a separate question in itself. I think that this still need to be asked. $\endgroup$ –  justANewbie May 21, 2023 at 10:48
  • $\begingroup$ Yes, nothing wrong with the question. Just pointing out that there are more approaches to addressing this issue than just the choice of syntax for the two operators ─ and indeed, some languages use the same syntax = for both things because the context determines whether it's a name binding or an equality check. $\endgroup$ –  kaya3 May 21, 2023 at 12:02
  • $\begingroup$ so are you asking particularly about design strategies to prevent these kinds of mistakes? Because I don't see that represented in your title, and if you are (asking about that), it should be (represented in your title) $\endgroup$ –  starball May 21, 2023 at 19:03
  • 3 $\begingroup$ Not syntax, but in Swift assignment expressions are of type void, so this error can't happen either. $\endgroup$ –  chrysante May 21, 2023 at 21:36

17 Answers 17

Just throw unicode symbols at it (the apl way).

APL uses ← for assignment and = / ≡ for equality ( = is term-wise, ≡ is for the whole array). If you can afford to just throw Unicode at the problem, sometimes it's a fun solution :) really depends on how the language is meant to be written, though.

RubenVerg's user avatar

  • 1 $\begingroup$ Not just Unicode have those symbols. Some calculators' BASIC dialects use ← as assignment too, from their limited character set. $\endgroup$ –  Longinus May 22, 2023 at 1:52
  • 1 $\begingroup$ Some dialects of Smalltalk use _ for assignment, because early versions of ASCII had an arrow at that codepoint. $\endgroup$ –  Bbrk24 May 22, 2023 at 4:16
  • $\begingroup$ @Longinus sure, but nowadays SBCS's are basically just Unicode mappings. I'd assume modern implementations of those BASIC's just read the (potentially sbcs-encoded) file and then display it as Unicode. $\endgroup$ –  RubenVerg May 22, 2023 at 5:03
  • $\begingroup$ I can't really tell if this answer is serious. If it is, how do you expect users to type these symbols? $\endgroup$ –  chrysante May 27, 2023 at 20:29
  • 1 $\begingroup$ @chrysante It is completely serious. In Dyalog APL, you'd hit your APL key (backtick by default) and then [ . $\endgroup$ –  RubenVerg May 27, 2023 at 21:27

Distinguish Assignment and Equality by Context

Some languages use = for both assignment and equality. The way the language differentiates the two use cases is by constraining the grammar so it's obvious which context is meant.

For instance, in BASIC, there is no such thing as an "expression statement", so if you write something like x=1 on a line by itself, the only possible interpretation is that you are assigning 1 to x . The alternative interpretation of "check if x is equal to 1 and discard the result" isn't an allowed interpretation in the language. This is in contrast to a language like C where both interpretations are legal (and thus, the compiler needs an additional symbol to disambiguate the two interpretations). Some languages also use a keyword like let or set to begin an assignment statement which can also help distinguish the two.

The advantage of having only one operator for both operations is that it simplifies the language. It also means that the compiler will never misinterpret your program because of a careless error. On the other hand, it is less expressive than languages that separate out the two operations. For instance, in C++, you can assign to variables within a condition or loop. In a language like BASIC, you cannot do this which may lead to more verbose code in some cases.

Isaiah's user avatar

Even though the OP sepcifically asks for different syntax to prevent this kind of error, I would make the case that a better approach is a semantic solution:

The reason why this error can occur in C++ (and in C for that matter) is that an assignment expression evaluates to a reference to the assigned variable ( int& in this case) and that int is implicitly convertible to bool (*). By changing either of these properties we can prevent this error.

If we forbid implicit narrowing conversions or just the implicit int -> bool conversion we are already fine. This however prevents the following common C idiom:

But I would argue that this alternative code is easier to understand and just as simple to write:

If we evaluate assignment expressions not to a reference to the assigned value but to void we also solve the problem, but this time we prevent this idiom:

However this is rarely used and confusing if not seen before, and the alternative

is not significantly more verbose (and much clearer), so I would argue that losing this idiom is also not much of a loss if not an improvement.

So in conclusion I argue that while either of the approaches solves the problem, both of them are reasonable in their on right and can prevent other possible code smells.

Also now you are free to choose whatever syntax you like without the restriction of having to solve this problem.

(*) On top of that, in clauses of if statements, also explicit conversions to bool are considered in C++. This rule exists so class authors can make conversions to bool explicit, which prevents implicit conversions from the custom type to integral types (via class X -> bool -> int ) while still allowing the class to be used as a condition in if statements, but in our case it makes matters worse.

chrysante's user avatar

  • 1 $\begingroup$ An alternative is only forbidding raw assignment in a boolean context. Extra-parentheses are cheap enough. Also, if a , b and/or c are long and/or expressions with side-effects, the rewrite will be quite cumbersome and not actually that trivial. $\endgroup$ –  Deduplicator Jul 3, 2023 at 15:44
  • $\begingroup$ @Deduplicator If a , b or c are complex expressions, you can store them to temporaries. That's what the compiler does under the hood if you write a nested assignment expression anyhow. I agree that forbidding raw assignment in if-conditions is also a solution, but that does not prevent the error in other boolean expressions. $\endgroup$ –  chrysante Jul 3, 2023 at 16:38

The Pascal way

i.e using := for assignment and = for equality check.

The example in the question can be written in Pascal as:

This is so harder to mistype the two.

  • 2 $\begingroup$ Just as a note about this, := was chosen because it looked a bit like the left-arrow symbol in mathematics, ⟸, but wouldn't be confused for "less than or equal to". Prolog uses :- for a similar reason. $\endgroup$ –  Pseudonym May 22, 2023 at 1:02
  • 5 $\begingroup$ @Pseudonym I believe the := symbol exists in mathematics as well, and has the meaning of introducing the definition for a new variable. The double arrows, on the other hand, I've never seen used for anything besides implication. Might be a case of poorly internationalized syntax, though) $\endgroup$ –  abel1502 May 27, 2023 at 16:26
  • $\begingroup$ That's what I am doing in my programming language, AEC . $\endgroup$ –  FlatAssembler Jul 10, 2023 at 18:47

The GNU solution to the if(x = y) {} problem is to require double parenthesisation where only if((x = y)) {} is unambiguous. That said, to mean assignment, the = , := , <- and ← operators are common across many languages descending from C, Pascal and BASIC. Vale uses a set keyword to mean reassignment.

In languages where the concept of "(re)assignment" does not exist, like most Functional and Logical ones, it is not uncommon to see = be used both for bindings and as the equality binary operator, along with == . For instance, in a language lacking builtin mutation support, this code is unambiguous:

Some English-oriented languages, like CoffeeScript , also use a is keyword.

For completeness, are also common as inequality operators != , /= , <> , ≠ and isnt , all used in various languages.

Longinus's user avatar

Common Lisp

Most of the time when you need a variable, you'll use let .

There's also setf .

Equality checking looks like one of the following (depending on what exactly you want—there are more equality operators).

It's really hard to accidentally mix the two up.

Aman Grewal's user avatar

Use : , like JSON

Assignment and comparison have different purposes, return values, and allowed syntactic locations. Therefore, they should be represented with bigger differences than a single extra character.

The use of : for "assignments" is already fairly common and should be familiar to users:

  • JSON/object notation: uses colon to bind a value to a key.
  • English: like this list, where a colon associates a value or comment with an entry.

This gives you a one-character solution for assignment, leaves = free for equality, and should be immediately clear to readers.

BoppreH's user avatar

  • $\begingroup$ : is used for assignment in K and Q. $\endgroup$ –  Adám Oct 11, 2023 at 21:51

It partly depends on the semantics of variables and the semantics of equality.

Some languages distinguish between intensional and extensional equality . One example of this might be a set of integers represented as a binary search tree. Two sets are intensionally equal if the trees have the same structure, but extensionally equal if the numbers in the sets are the same.

Yet other languages have different notions of equality testing that depends on whether or not they will coerce types. Does 3 == 3.0 in a dynamically typed language? Sometimes you want that and sometimes you don't.

Other languages have object identity, which is different from equality.

This is a lot of symbols for equality testing that you might need to invent! Common Lisp has four of them.

Logic languages have only one symbol = , and it means unification . Just looking at simple values like numbers for the moment, if you type X = Y , then it can mean several things:

  • If X is a free variable but Y has a value already bound to it, this assigns that value to X .
  • Same thing if Y is free but X is bound; this is left-assignment.
  • If X and Y are both bound, then this is an equality test.
  • If X and Y are both free, then this aliases the two variables together. A subsequent binding of X will automagically also bind Y .

In general, X and Y could be data structures with some bound and some unbound variables inside it, in which case the full unification algorithm is run.

Pseudonym's user avatar

In Assembly ( mov ) or more basic languages there is a keyword for assignment, such as:

I am personally not a fan of this because I prefer punctuation as operators, but this is an option that resolves ambiguity.

Or in Assembly:

CPlus's user avatar

Different Spellings

Other common variations for assignment are := and (so far unmentioned) <- . JavaScript is notorious for having many different comparison operators.

Vale has the interesting variation that x = 42 is only a variable declaration, and assignment must be written set x = 42 . I find, like the author, that I also write many more dclarations than assignments.

Different Semantics

A functional language, using static single assignments, or one using linear types , allows assignment only within bindings, which can be marked with let . Alternatively, since newer languages tend to discourage mutability and assignments, you could mark assignments with set , or do both. Since is is no longer than == and be or to no longer than := or <- , this could be valid syntax:

Davislor's user avatar

Modern programming languages like Go use the "="/":=" for assignment and "==" for the comparison. It gives a compile time error if you mistype "=" instead of "==". Another suggestion would be to use constants when comparing, but that wouldn't solve your problem with mistyping in C++.

user514's user avatar

  • $\begingroup$ Welcome to PLDI. How does your answer differ from justANewbie's answer? $\endgroup$ –  Isaiah May 21, 2023 at 16:03
  • $\begingroup$ @Isaiah Pascal uses = for equality comparison, and Go uses == for equality comparison. The point is that Go allows = instead of := for assignment when it's not in an expression. This is also the same as Python ─ = is assignment but not an expression, := is an assignment expression, == is an equality comparison. $\endgroup$ –  kaya3 May 21, 2023 at 17:53
  • 4 $\begingroup$ "Modern programming languages like F# use = for both bindings and equality." It's a bold move to make a blanket statement like "modern PLs do x " when they disagree with each other on how to do x . $\endgroup$ –  Longinus May 22, 2023 at 1:56

Coming relatively out of left field is Swift’s pattern-matching operator ~= . It’s rarely written in source, instead the result of desugaring a switch or if case statement, but you could use it instead of == for regular equality comparison if you wanted to.

Bbrk24's user avatar

The original Smalltalk uses ← for assignment and = for equality. It also uses ↑ for return.

The original Smalltalk developed at Xerox used its own workstation developed at Xerox with its own CPU developed at Xerox and its own input devices (keyboard and mouse) developed at Xerox. Smalltalk was its own Operating System as well.

All this to say that it also had its own character set and character encoding.

When Smalltalk first was ported to other systems using the ASCII character encoding, it turned out that ASCII had the character ^ at the same code point where Smalltalk had ↑ , so all Smalltalk was rendered with ^ for return on machines that used ASCII. It still looks like an upwards arrow, so it still kind of works.

Assignment was not so lucky, though: where Smalltalk had ← , ASCII has _ , so all assignments in Smalltalk were rendered as _ in ASCII. This was somewhat unsatisfactory, so it was decided to change the language specification use := for assignment. However, some Smalltalks still accept _ even today.

Jörg W Mittag's user avatar

  • $\begingroup$ I mentioned this in a comment on another answer, but this is much more thorough (as is expected from the nature of comments). $\endgroup$ –  Bbrk24 Jul 6, 2023 at 17:05

Use ,= or ;=

We could already understand ,= as the += -like version of , in C-style operators. And ;= looks less confusing, if you already merge , with ; .

user23013's user avatar

Most compiler have the decency to give you a warning if you use the wrong operator, or if the compiler isn't sure. For example, with a good C compiler I expect that

gives a warning. And if I really want to store 1234 and then examine whether it is zero, these compilers may allow

which tells the compiler "be quiet, I know what I'm doing".

Newer languages don't allow integers to be used as boolean values. So the first example might not compile if the = operator doesn't yield a result, or it yields an integer result which cannot be used in an "if" statement. That's assuming that

would be very rare.

You could use different pairs of tokens. := and =, or = and .eq. like FORTRAN did, or a leftarrow for assignment. The warning, and possible changed semantics, is the simplest solution. In the end, if the code you type is not the code you wanted, that's your problem.

gnasher729's user avatar

You can raise an error

For example this code in Python is correct:

raise an error (no confusing bug like C++):

You must log in to answer this question.

Not the answer you're looking for browse other questions tagged syntax language-design ., hot network questions.

  • What scientific evidence there is that keeping cooked meat at room temperature is unsafe past two hours?
  • Is it allowed to use patents for new inventions?
  • Is cellulose, blown-in insulation biodegradeable?
  • Why does mars have a jagged light curve
  • How big can a chicken get?
  • British child with Italian mother. Which document can she use to travel to/from Italy on her own?
  • What did the old woman say in "73 Yards"?
  • Parody of early D&D rules set, and specifically character creation, as part of a web novel of some kind
  • Why is "second" an adverb in "came a close second"?
  • Lotto Number Generator - Javascript
  • Improvising if I don't hear anything in my "mind's ear"?
  • What is the origin of the idiom "say the word"?
  • Is it correct to say: My friend can play more instruments than my A's at school?
  • What is the difference between Hof and Bauernhof?
  • Selecting an opamp for a voltage follower circuit using a LTspice simulation
  • Negative Horizon distance
  • How to make Bash remove quotes after parameter expansion?
  • Python script to auto change profiles in MSI Afterburner
  • Expected Amp difference going from SEU-AL to Copper on HVAC?
  • Was it known in ancient Rome and Greece that boiling water made it safe to drink and if so, what was the theory behind this?
  • siblings/clones tour the galaxy giving technical help to collapsed societies
  • How should I join sections of concrete sidewalk poured in stages?
  • Am I seeing double? What kind of helicopter is this, and how many blades does it actually have?
  • Is it possible to convert a Bézier curve to a NURBS curve while preserving the curve?

possibly incorrect assignment in c

incorrect assignment

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Compiler Warning (level 2) CS0728

  • 7 contributors

Possibly incorrect assignment to local 'variable' which is the argument to a using or lock statement. The Dispose call or unlocking will happen on the original value of the local.

There are several scenarios where using or lock blocks will result in a temporary leak of resources. Here is one example:

thisType f = null;

f = new thisType();

In this case, the original value, such as null, of the variable thisType will be disposed of when the using block finishes executing, but the thisType object created inside the block will not be, although it will eventually get garbage collected.

To resolve this error, use the following form:

using (thisType f = new thisType())

In this case, the newly allocated thisType object will be disposed of.

The following code will generate warning CS0728.

Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see: https://aka.ms/ContentUserFeedback .

Submit and view feedback for

Additional resources

Log in or Sign up

You are using an out of date browser. It may not display this or other websites correctly. You should upgrade or use an alternative browser .

possibly incorrect assignment in c

Possibly incorrect assignment (C++)

Discussion in ' Programming & Software Development ' started by Mac No Pickle , Sep 2, 2005 .

Mac No Pickle

Mac No Pickle Member

I'm relativly new to programming in C and seem to be running into a problem. The error message on compiling Code: C:\gp\ass>bcc32 test.c Borland C++ 5.5.1 for Win32 Copyright (c) 1993, 2000 Borland ass1.c: Warning W8060 test.c 231: Possibly incorrect assignment in function turnOnVP Turbo Incremental Link 5.00 Copyright (c) 1997, 2000 Borland What happens when I run it. Code: C:\gp\ass>test Right viewport = off Right viewport = off Right viewport = off Right viewport = off The relevent code Code: /*defined in the global portion of the program*/ GLboolean rightVPortOn = GL_FALSE; /*The program runs and detects the keyboard input **of 'd'. It then calls turnOnVP(); */ void turnOnVP(void){ if(rightVPortOn = GL_FALSE){ rightVPortOn = GL_TRUE; printf("%s\n","Right viewport = on"); }else{ rightVPortOn = GL_FALSE; printf("%s\n","Right viewport = off"); } } /*line 231 is here*/ As you can see by the output above the if statement always goes to false. To fix it I've tried usin GLint, GLboolean, and int datatypes, however it still has the same compile and runtime error. I've also had a quick google but can't seem to find much help (probably using the wrong terms). Can any of you guys help  

SomeGuy1234

SomeGuy1234 Member

The if statement only has one "=" which is the assignment operator, the "==" is the equality operator. What yours is doing is trying to make rightVPortOn the value of GL_FALSE, when it does this if it can assign it, it returns true, yours however returns false because it's a constant and it cant re-assign a constant. Corrected: Code: /*defined in the global portion of the program*/ GLboolean rightVPortOn = GL_FALSE; /*The program runs and detects the keyboard input **of 'd'. It then calls turnOnVP(); */ void turnOnVP(void){ if(rightVPortOn == GL_FALSE){ rightVPortOn = GL_TRUE; printf("%s\n","Right viewport = on"); }else{ rightVPortOn = GL_FALSE; printf("%s\n","Right viewport = off"); } } /*line 231 is here*/  
Awesome, thanks for that. I should have know it'd be something simple like that  

Share This Page

  • No, create an account now.
  • Yes, my password is:
  • Forgot your password?

OCAU Forums

Having troubles when I run my program

USing NeHe’s tutorial I have just typed in all of lesson 1, but when I run it there is some warning/error :“W8060 possibly incorrect assignment”

Is that because I use C++ builder, as discused in my other thread ?

the lines it is warning about says :

if (!(hRC=wglCreateContext(hDC))) { KillGLWindow(); MessageBox(NULL,“Can’t create a GL rendering context”,“ERROR”,MB_OK|MB_ICONEXCLAMATION); return FALSE; }

If it is due to me using builder, then what can i do to make it work in builder ?

The program works though… so it’s not like i can’t live with these warnings(4 og them) but I would like them to be gone =)

[This message has been edited by Nomaden (edited 07-21-2000).]

U are right, it is builder specific…welll i dont know bout others but i know msvc++ dfont care. Its actually helpful though…the most commonn programming error…: when u want: if(a == b) but u put: if(a = b) !!! this thing warns u about assignments in if statements!!! i would love for msvc++ to do that, i have made that mistake so many times!

if you REALLY care… then what you could do is try to find a #pragma option or something? I know that you can disable warnings when you do implicit conversions from one data type to another… so, maybe there is an option for something like this?

Okay guys… Thanks. I will try and find some way to turn these warnings of, and if I can’t find them, then my boss is going to buy me MSVC++… hehe

  • Windows Programming
  • UNIX/Linux Programming
  • General C++ Programming
  • Visual Studio C++ warning C4829: Possibl

  Visual Studio C++ warning C4829: Possibly incorrect parameters to function main.

possibly incorrect assignment in c

main(array<String^>^ args) { }
main() { std::cout << ; }
  • Open Source Software
  • Business Software
  • For Vendors
  • SourceForge Podcast
  • Site Documentation
  • Subscribe to our Newsletter
  • Support Request

Borland Warnings in init.c

  • Feature Requests
  • Create Ticket
  • Closed Tickets
  • Open Tickets
  • Formatting Help

#23 Borland Warnings in init.c

Borland BCC32 compiler version 5.6.4 produces the following warnings when compiling init.c from the CVS.

! Warning W8060 ..\..\..\..\libmss\init.c 85: Possibly incorrect assignment in function mss_open_logfiles ! Warning W8001 ..\..\..\..\libmss\init.c 142: Superfluous & with function in function mss_startup ! Warning W8001 ..\..\..\..\libmss\init.c 143: Superfluous & with function in function mss_startup ! Warning W8001 ..\..\..\..\libmss\init.c 144: Superfluous & with function in function mss_startup ! Warning W8071 ..\..\..\..\libmss\init.c 152: Conversion may lose significant digits in function mss_startup ! Warning W8001 ..\..\..\..\libmss\init.c 161: Superfluous & with function in function mss_startup ! Warning W8065 ..\..\..\..\libmss\init.c 237: Call to function 'mss_log_list_blocks_internal' with no prototype in function mss_exit

Here are the explanations from the Borland Help file:

W8060 Possibly incorrect assignment This warning is generated when the compiler encounters an assignment operator as the main operator of a conditional expression (part of an if, while, or do-while statement). This is usually a typographical error for the equality operator. If you want to suppress this warning, enclose the assignment in parentheses and compare the whole thing to zero explicitly. For example, this code if (a = b) ... should be rewritten as if ((a = b) != 0) ...

W8001 Superfluous & with function An address-of operator (&) is not needed with function name; any such operators are discarded.

W8071 Conversion may lose significant digits For an assignment operator or some other circumstance, your source file requires a conversion from a larger integral data type to a smaller integral data type where the conversion exists. Because the integral data type variables don't have the same size, this kind of conversion might alter the behavior of a program.

W8065 Call to function 'function' with no prototype This message is given if the "Prototypes required" warning is enabled and you call function 'function' without first giving a prototype for that function.

Charles Brockman

Logged In: YES user_id=250965

Warning W8060 ..\..\..\..\libmss\init.c 85: Possibly incorrect assignment in function mss_open_logfiles

I changed line 85 to if (!(mss_slogfile = fopen(MSS_SLOG_FILENAME, mode) == NULL)) which makes it similar to line 101 but then got the additional warning Warning W8069 ..\..\..\..\libmss\init.c 86: Nonportable pointer conversion in function mss_open_logfiles Does that assignment involve dissimilar types?

Warning W8001 ..\..\..\..\libmss\init.c 142: Superfluous & with function in function mss_startup Warning W8001 ..\..\..\..\libmss\init.c 143: Superfluous & with function in function mss_startup Warning W8001 ..\..\..\..\libmss\init.c 144: Superfluous & with function in function mss_startup

Changed lines 142, 143 and 144 to dcflist_create_sorted(&mss_list, mss_free_node_object, mss_compare_node_objects); dcflist_create(&mss_scope, mss_free_scope_object);

Warning W8071 ..\..\..\..\libmss\init.c 152: Conversion may lose significant digits in function mss_startup This is similar to the warning in log.c (bug report 1157914). Perhaps there is a type mismatch here also.

Warning W8001 ..\..\..\..\libmss\init.c 161: Superfluous & with function in function mss_startup

I changed line 161 to: if (atexit(mss_exit) != 0)

Index: init.c

RCS file: /cvsroot/libmss/libmss/init.c,v retrieving revision 1.10 diff -r1.10 init.c 142,144c142,144 < dcflist_create_sorted(&mss_list, &mss_free_node_object, < &mss_compare_node_objects); < dcflist_create(&mss_scope, &mss_free_scope_object); --- > dcflist_create_sorted(&mss_list, mss_free_node_object, > mss_compare_node_objects); > dcflist_create(&mss_scope, mss_free_scope_object); 161c161 < if (atexit(&mss_exit) != 0) --- > if (atexit(mss_exit) != 0)

Laurynas Biveinis

  • assigned_to : lauras --> nobody

Log in to post a comment.

possibly incorrect assignment in c

  • Election 2024
  • Entertainment
  • Newsletters
  • Photography
  • Personal Finance
  • AP Investigations
  • AP Buyline Personal Finance
  • AP Buyline Shopping
  • Press Releases
  • Israel-Hamas War
  • Russia-Ukraine War
  • Global elections
  • Asia Pacific
  • Latin America
  • Middle East
  • Election Results
  • Delegate Tracker
  • AP & Elections
  • Auto Racing
  • 2024 Paris Olympic Games
  • Movie reviews
  • Book reviews
  • Personal finance
  • Financial Markets
  • Business Highlights
  • Financial wellness
  • Artificial Intelligence
  • Social Media

Powder kegs: 50 years ago, 10-cent beers helped turn a Cleveland baseball game into a bloody riot

FILE - In this image provided by Special Collections, Cleveland State University, Texas Rangers' Jeff Burroughs, center, runs off the field with his teammates during the Beer Night melee at Cleveland Stadium, June 4, 1974, in Cleveland. The Cleveland Indians forfeited the baseball game to the Rangers after fans, fueled by 10-cent beers, stormed the field in the ninth inning. (Paul Tepley/Cleveland Press, Special Collections, Cleveland State University, via AP, File)

FILE - In this image provided by Special Collections, Cleveland State University, Texas Rangers’ Jeff Burroughs, center, runs off the field with his teammates during the Beer Night melee at Cleveland Stadium, June 4, 1974, in Cleveland. The Cleveland Indians forfeited the baseball game to the Rangers after fans, fueled by 10-cent beers, stormed the field in the ninth inning. (Paul Tepley/Cleveland Press, Special Collections, Cleveland State University, via AP, File)

FILE - In this image provided by Special Collections, Cleveland State University, injured umpire Nestor Chylak, right, leads his crew, from left, Joe Brinkman, Nick Bremigan, and Larry McCoy off the field during the Beer Night melee at Cleveland Stadium, June 4, 1974, in Cleveland. The Cleveland Indians forfeited the baseball game to the Rangers after fans, fueled by 10-cent beers, stormed the field in the ninth inning. (Paul Tepley/Cleveland Press, Special Collections, Cleveland State University, via AP, File)

  • Copy Link copied

CLEVELAND (AP) — Beer flowed and a little blood and bruises followed. There was some baseball played in between.

On a warm spring night along Lake Erie five decades ago, a well-intended promotion meant to attract fans for the perpetually lousy Cleveland Indians turned ugly and triggered a booze-fueled riot now known as one of the most notorious events in American sports history.

On Tuesday, 10-cent beer night turns 50.

Cheers. Burp.

A game that began with a handful of fans tipsy on cheap beer running across the outfield grass — some of them naked — collapsed into chaos.

During a scary ninth inning, Texas manager Billy Martin, never one to back down from a fight, turned to his players in the dugout and told them to grab bats before leading a charge onto the Municipal Stadium field and into mayhem.

Looking back to June 4, 1974, it’s hard to imagine that anyone thought it would be a good idea to sell beers for just a dime. But it was a different world then, maybe not innocent but certainly naive.

By the time the Rangers escaped to their clubhouse with a win via forfeit after surviving hundreds of fans storming the field as the Indians were rallying, it became apparent this was a big mistake.

Seattle Mariners' Cal Raleigh flips his bat after hitting a game-winning grand slam against the Chicago White Sox during the ninth inning of a baseball game Monday, June 10, 2024, in Seattle. (AP Photo/Lindsey Wasson)

“It kind of fit in with the times,” said former Cleveland manager Mike Hargrove, who was a 24-year-old rookie first baseman with the Rangers. “They had Disco Demolition Night in Chicago, and to me it was almost a sign of what was to come 50 years later with all that’s going on in the world right now.”

Even before the first keg was tapped or 10-ounce beer poured, there already was simmering tension between the Rangers and Indians. A week earlier, the teams had brawled in Texas, where Rangers fans pelted the Indians players with debris.

After the skirmish, Martin lit a proverbial match when asked if he feared retribution on an upcoming trip to Cleveland.

“They don’t have enough fans there to worry about,” he quipped.

The comment didn’t sit well back in Cleveland, where civic pride runs deeper than the Cuyahoga River and passionate fans aren’t averse to quaffing a brew or two while watching their pro sports teams.

In the week leading up to 10-cent Beer Night, local radio host Pete Franklin fanned flames by vowing revenge against the Rangers. Martin was booed when he presented the lineup card.

Hargrove sensed trouble long before being pelted with dozens of hot dogs thrown from the stands. He barely dodged being hit by a wine bottle.

“About the second inning, fans started running back and forth across the outfield from the left-field bullpen to the right-field bullpen,” Hargrove told The Associated Press in a phone call last week. “It started out with a couple of people doing it and then it was five, then 10, and then it was a whole bunch.”

From his seat in the upper deck, Jack Barno, who went to the game with high school buddies, could see things were escalating in a bad way.

“When people were streaking across the field and the cops were chasing them, they were laughing like, ‘You can’t catch me,’” recalled the 67-year-old resident of Westlake, Ohio. “There was a handful of cops on the other side with billy clubs. And when they came over that fence, they met them with a couple whacks to the head and dragged them off.”

Other problems percolated around the giant ballpark.

With long lines making their wait too long to get a refill, unruly fans, some of them college kids just home for summer break, chased off concession workers manning the beer trucks set up beyond the center-field wall. The beer was now free.

Stadium security was outnumbered and overwhelmed by the crowd of 25,134, the season’s second-largest.

Still, it was mostly good-natured fun — a woman ran onto the field and tried to kiss umpire Nestor Chylak. A father and son mooned the crowd.

Then came the ninth and a scene from a low-budget horror film.

After trailing 5-3, the Indians scored twice to tie it and had runners on when a fan scaled the outfield wall, sprinted toward Rangers right fielder Jeff Burroughs and tried to steal the player’s cap.

In the dugout, Martin screamed for his players to follow him. Hargrove headed to right to assist Burroughs, who at that point had been surrounded. The Indians burst from their dugout to help the Rangers.

“Some great big guy, drunk guy took Jeff’s hat, and I was one of the first ones to get there,” Hargrove said. “I tackled him and knocked him down and it took like three cops to handcuff him. Thank goodness he was on the ground. I took off — or else.”

The rest is something of a hazy blur.

“I remember nothing about the game, other than in that inning we were in trouble,” Hargrove said. “They had runners on and it looked like they were getting ready to score and go ahead and then all of a sudden all hell broke loose.”

While most players escaped major harm, Indians pitcher Tom Hilgendorf’s head was split open by a chair thrown from the stands as fights broke out all over the field.

Even a half-century later, Hargrove can recall his emotions from the unforgettable night.

“I don’t remember being scared,” he said. “I don’t remember feeling like I was threatened. I didn’t feel that way when it was going on until we got to the clubhouse looking back out there at what went on and could have gone on.

“Then, I got a little shaky.”

While the night was another blow to the city’s already battered image, Clevelanders mostly shrugged. Today, the ugly event is commemorated with throwback T-shirts marking the night beer, blood and baseball mixed.

The rest of the country was outraged.

The Indians held another beer night a month later.

This story has been corrected to show that the woman who tried to kiss umpire Nestor Chylak was not identified and the person hit by a chair was Indians pitcher Tom Hilgendorf, not Chylak.

AP MLB: https://apnews.com/hub/mlb

possibly incorrect assignment in c

  • Stack Overflow Public questions & answers
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Talent Build your employer brand
  • Advertising Reach developers & technologists worldwide
  • Labs The future of collective knowledge sharing
  • About the company

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Why would you use an assignment in a condition?

In many languages, assignments are legal in conditions. I never understood the reason behind this. Why would you write:

instead of:

  • conditional-statements
  • language-agnostic
  • variable-assignment

Peter Mortensen's user avatar

  • 2 Is this question really so language-agnostic? Which languages are affected by this? I know C and C++ are, what else? –  Wolf Apr 23, 2019 at 9:33
  • What other languages besides C and C++ allow this (without a compile-time or run-time error)? PHP? Perl? –  Peter Mortensen Jun 26, 2022 at 15:26
  • Note : The canonical question for the common programming error associated with this (unintentional assignment) is Variable assignment in "if" condition (even if it is from 2013). –  Peter Mortensen Jun 30, 2022 at 13:39
  • As expected, there is also a question from 2008 (but search engines don't like to point to it). –  Peter Mortensen Jun 30, 2022 at 17:27
  • Tell me about it. Just wasted 1 hour as there isnt even a warning in vscode that I had used = instead of == for a normal conditional test. –  Johncl Feb 15, 2023 at 14:52

12 Answers 12

It's more useful for loops than if statements.

Which would otherwise have to be written

Gerald's user avatar

  • 14 I agree - but would write: while ((var = GetNext()) != 0) { ... } without thinking twice, partly because GCC complains if I don't with my default compilation options. –  Jonathan Leffler Oct 8, 2008 at 22:08
  • 1 True. Assuming you're using a language that supports for-loop declarations, and you're not already using var outside of the loop. –  Gerald Oct 24, 2012 at 16:02
  • 1 in Some languages, like ANSI C, scoping rules don't permit this approach, @KerrekSB –  wirrbel Oct 9, 2013 at 16:30
  • 7 @wirrbel: You mean ANSI C from what, 1989? Like when they had steam engines and punch cards? That may be the case, but is that relevant? –  Kerrek SB Oct 9, 2013 at 18:18
  • 3 That warning is not because there is anything wrong with an assignment in a while, but because doing an assignment when you really meant to do a comparison is a common bug. If you want to get rid of the warning you can do the JS equivalent of what @Jonathan Leffler suggests. Personally I would probably do that anyway because of how much I mistrust the JavaScript truthy rules :) It should also be noted in some languages like C# and Java that is the only way. –  Gerald Jun 19, 2015 at 9:16

I find it most useful in chains of actions which often involve error detection, etc.

The alternative (not using the assignment in the condition) is:

With protracted error checking, the alternative can run off the RHS of the page whereas the assignment-in-conditional version does not do that.

The error checks could also be 'actions' — first_action() , second_action() , third_action() — of course, rather than just checks. That is, they could be checked steps in the process that the function is managing. (Most often in the code I work with, the functions are along the lines of pre-condition checks, or memory allocations needed for the function to work, or along similar lines).

Jonathan Leffler's user avatar

  • Yeah, I actually did just this to avoid excessive nesting and then searched online to see if it was a common practice. In the end I decided against it because I actually only had one else case, but this seems like a legitimate reason to put the assignment in the condition. –  Ibrahim Oct 1, 2013 at 18:28
  • Coworkers hate it! To me, at least in most cases, is far more maintainable than a giant tree or many returns. I prefer single return from a function... –  Nathan Feb 3, 2017 at 0:50
  • a reasonable example, the acompanion blocks make the pattern obvious, self-explanatory. But, well, the in-block ("pseudo") code looks a bit ugly, and the inverse style (placing what you really wanted to do at the end) isn't that great. –  Wolf Apr 23, 2019 at 9:39

It's more useful if you are calling a function:

Sure, you can just put the n = foo(); on a separate statement then if (n), but I think the above is a fairly readable idiom.

Chris Young's user avatar

  • 4 I think you should enclose it in parenthesis or gcc will complain with: warning: suggest parentheses around assignment used as truth value [-Wparentheses] Like this: if ((n = foo())) { // do something with the return value } else { // foo returned zero/NULL, do something else } –  Fabio Pozzi Jul 17, 2015 at 12:41

It can be useful if you're calling a function that returns either data to work on or a flag to indicate an error (or that you're done).

Something like:

Personally it's an idiom I'm not hugely fond of, but sometimes the alternative is uglier.

Michael Burr's user avatar

GCC can help you detect (with -Wall) if you unintentionally try to use an assignment as a truth value, in case it recommends you write

I.e. use extra parenthesis to indicate that this is really what you want.

JesperE's user avatar

  • 3 Good to know. I hope your co-workers read it in the same manner. –  Wolf Apr 23, 2019 at 9:53
  • 1 Me? Goodness, I would never try to use assignment as a truth value. I was referring to what GCC recommends. –  JesperE May 24, 2019 at 5:51
  • GCC can also compile Fortran . Perhaps be explicit about the programming language? –  Peter Mortensen Jul 19, 2020 at 6:20
  • I much prefer the explicit if ((n = foo()) != 0) to avoid quite so many consecutive close parentheses, but I admit that you can increase the number of consecutive ) by notations such as if ((n = foo2(a, somefunc(b, sizeof(SomeType)))) != 0) –  Jonathan Leffler Apr 13, 2022 at 14:43

The idiom is more useful when you're writing a while loop instead of an if statement. For an if statement, you can break it up as you describe. But without this construct, you would either have to repeat yourself:

or use a loop-and-a-half structure:

I would usually prefer the loop-and-a-half form.

Greg Hewgill's user avatar

  • 1 For a while loop, prefer using: do { c = getchar(); ... } while (c != EOF); –  Scott S Nov 1, 2018 at 17:25
  • And for loops can be used instead: for (char c = getchar(); c != EOF; c= getchar()) { /* do something with c */ } -- this is the most concise, and for always says 'loop' to me, stylistically. Small downside is that you have to specify the function returning c twice. –  Scott S Nov 1, 2018 at 17:29

The short answer is that expression-oriented programming languages allow more succinct code. They don't force you to separate commands from queries .

Hugh Allen's user avatar

  • 1 It is a constant fight to enforce coding without assignments in if(), while(), and other similar statements. C/C++ are notorious for side effects of such that often turn out to be bugs, especially when we add the ++ and -- operators. –  Alexis Wilke Sep 4, 2012 at 0:02
  • 1 The first link is useless: C or C++ seem not to be such a language. –  Wolf Apr 23, 2019 at 9:58

In PHP, for example, it's useful for looping through SQL database results:

This looks much better than:

Paige Ruten's user avatar

  • 5 This also has the neat side-effect of $row not living beyond that loop and therefore being eligible for garbage collection sooner (in languages that do GC anyway). –  Darren Greaves Sep 30, 2008 at 5:39

The other advantage comes during the usage of GDB .

In the following code, the error code is not known if we were to single step.

Now during single stepping, we can know what was the return error code from the checkstatus().

plasmixs's user avatar

  • 1 You mean that it can be helpful for temporary changes when debugging code? –  Wolf Apr 23, 2019 at 10:01

I find it very useful with functions returning optionals ( boost::optional or std::optional in C++17):

This reduces the scope of my variable, makes code more compact and does not hinder readability (I find).

Same with pointers:

Julien-L's user avatar

  • By the way, if you want to limit the scope of variables, you can use if with initializers :) –  cigien Oct 25, 2020 at 4:37

I used it today while programing in Arduino (Subset of C++ language).

I have a transmitter and a receiver. The transmitter wants to send the data until it is received. I want to set a flag when the process is done.

  • "transmitter.send" - returns true when the transmission is successful
  • "newtork_joined " - is the flag I set when successful

When the transmission is not successful, the flag is not set, while loop is true, it keeps executing

When successful, the flag is set, while loop is false, we exit

Isn't beautiful?

Priteem's user avatar

  • Re "in Arduino (C language" : Arduino's programming language is for the most part a subset of C++ (not C)—though it is not entirely clear what it is. For instance, it has class 'string' (e.g., operator "+= " defined for it). This is definitely not C. –  Peter Mortensen Jun 26, 2022 at 15:29
  • @PeterMortensen, you are right. Let me edit. –  Priteem Jun 30, 2022 at 13:20

The reason is:

Performance improvement (sometimes)

Less code (always)

Take an example: There is a method someMethod() and in an if condition you want to check whether the return value of the method is null . If not, you are going to use the return value again.

It will hamper the performance since you are calling the same method twice. Instead use:

Gangadhar's user avatar

  • What language is this? It wouldn't compile in C# or C++ (capitalisation of "If"). –  Peter Mortensen Jul 19, 2020 at 6:23

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged conditional-statements language-agnostic variable-assignment or ask your own question .

  • Featured on Meta
  • The 2024 Developer Survey Is Live
  • The return of Staging Ground to Stack Overflow
  • The [tax] tag is being burninated
  • Policy: Generative AI (e.g., ChatGPT) is banned

Hot Network Questions

  • Using command defined with \NewDocumentCommand in TikZ
  • can you roll your own .iso for USB stick?
  • What terminal did David connect to his IMSAI 8080?
  • What changes the velocity perpendicular to radius in an elliptical orbit?
  • A short story in French about furniture that leaves a mansion by itself, and comes back some time later
  • Word for a country declaring independence from an empire
  • Net concentration of sodium hydroxide after addition of phenol red indicator
  • What is the status of the words "with him" in Romans 8:17?
  • In the Unabomber case, was "call Nathan R" really mistakenly written by a New York Times intern?
  • siblings/clones tour the galaxy giving technical help to collapsed societies
  • Am I seeing double? What kind of helicopter is this, and how many blades does it actually have?
  • Is the barrier to entry for mathematics research increasing, and is it at risk of becoming less accessible in the future?
  • Cryptic Clue Explanation: Tree that's sported to keep visitors out at university (3)
  • What's the maximum amount of material that a puzzle with unique solution can have?
  • What's the difference between cryogenic and Liquid propellant?
  • Ubuntu Terminal with alternating colours for each line
  • What happens when you target a dead creature with Scrying?
  • Why does mars have a jagged light curve
  • Can you use the special use features with tools without the tool?
  • How to negotiate such toxic competitiveness during my master’s studies?
  • Do you still cross out and redo the page numbers if you do it wrong in your scientific notebook?
  • Is it theoretically possible for the Sun to go dark?
  • Why is "second" an adverb in "came a close second"?
  • How can I use a router without gateway?

possibly incorrect assignment in c

IMAGES

  1. C programming +=

    possibly incorrect assignment in c

  2. Assignment Operators in C Example

    possibly incorrect assignment in c

  3. Assignment Operators in C with Examples

    possibly incorrect assignment in c

  4. Assignment Operators in C++

    possibly incorrect assignment in c

  5. C Programming Tutorial

    possibly incorrect assignment in c

  6. Assignment Operator in C Programming

    possibly incorrect assignment in c

VIDEO

  1. INORGANIC ASSIGNMENT C BY SHASHI SIR (9810657809)

  2. INORGANIC ASSIGNMENT C BY SHASHI SIR (9810657809)

  3. B. Ed 1st year assignment C-3

  4. B. Ed1st year assignment C

  5. B. Ed 1st year assignment C-7 Hindi

  6. B. Ed 1st year assignment C-2

COMMENTS

  1. c++

    while (p=strtok(NULL,",")) warning :possible incorrect assignment. Ask Question Asked 10 years, 4 months ago. Modified 10 years, 4 months ago. Viewed 386 times 2 There is a code and I am getting errors in. Line 8: array size too large line 9: array size too large line 28 while (p=strtok(NULL,",")) warning :possible incorrect assignment ...

  2. In C and C++, what methods can prevent accidental use of the assignment

    The problem is that the mistake was made by the C language "designers", when they chose to use = for the assignment operator and == for equality comparison. ALGOL used :=, because they specifically wanted to use = for equality comparison, and PASCAL and Ada followed the ALGOL decision.

  3. W8060 Possibly incorrect assignment (C++)

    W8060 Possibly incorrect assignment (C++) Go Up to Compiler Errors And Warnings (C++) Index. (Command-line option to suppress warning: -w-pia) This warning is generated when the compiler encounters an assignment operator as the main operator of a conditional expression (part of an if, while, or do-while statement).

  4. Chapter 4: Statement Formatting

    Warning test.c 5: Possibly incorrect assignment in function main. Never put an assignment statement inside any other statement. When to use two statements per line. Although there is a rule -- one statement per line -- don't be fanatical about it. The purpose of the rule is to make the program clear and easy to understand.

  5. 'Possibly Incorrect Assignment' warnings from Turbo-C

    No func will always be called and the result will be assigned to p. The compiler was only warning you that you might have made the same mistake

  6. C Language, warning: possibly incorrect assignment

    Message. Paul I. Wol. #1 / 9. warning: possibly incorrect assignment. Your compiler is conservatively trying to warn you that you may be. assigning instead of comparing FILE* objects with "==". You may be able to use an extra pair of parentheses to suppress the warning. "while ( (fp=fopen (file_name,"r")))", but it depends on your compiler.

  7. Warning Options (Using the GNU Compiler Collection (GCC))

    This option controls warnings when an attribute is ignored. This is different from the -Wattributes option in that it warns whenever the compiler decides to drop an attribute, not that the attribute is either unknown, used in a wrong place, etc. This warning is enabled by default. -Wmain ¶.

  8. C Assignment Operators

    The assignment operators in C can both transform and assign values in a single operation. C provides the following assignment operators: | =. In assignment, the type of the right-hand value is converted to the type of the left-hand value, and the value is stored in the left operand after the assignment has taken place.

  9. What alternatives are there for C/C++ assignment operator (=) and

    C/C++ use = for assignment and == for equality comparision. For example, a snippet in C++ can be like this: ... Most compiler have the decency to give you a warning if you use the wrong operator, or if the compiler isn't sure. ... or = and .eq. like FORTRAN did, or a leftarrow for assignment. The warning, and possible changed semantics, is the ...

  10. Solved: incorrect assignment

    Find answers to incorrect assignment from the expert community at Experts Exchange. Start Free Trial Log in. ... In DOS, using turbo C, which will be the final destination, Compilation provides the warning Possibly incorrect assignment in function counter_ (the underscore is to signal its the constructor, double _ is the destructor), the line ...

  11. Compiler Warning (level 2) CS0728

    Compiler Warning (level 2) CS0728. Possibly incorrect assignment to local 'variable' which is the argument to a using or lock statement. The Dispose call or unlocking will happen on the original value of the local. There are several scenarios where using or lock blocks will result in a temporary leak of resources.

  12. Possibly incorrect assignment (C++)

    The if statement only has one "=" which is the assignment operator, the "==" is the equality operator. What yours is doing is trying to make rightVPortOn the value of GL_FALSE, when it does this if it can assign it, it returns true, yours however returns false because it's a constant and it cant re-assign a constant. Corrected:

  13. errors with volume and area calculator

    "calculator.cpp": W8060 Possibly incorrect assignment in function main() at line 54: Thanks for the help! Tevsky. calculator.cpp": E2379 Statement missing ; in function volume() at line 42 W8070 Function should return a value in function volume() at line 43: You are missing a semi-colon on the line before 42 ...

  14. Having troubles when I run my program

    this thing warns u about assignments in if statements!!! i would love for msvc++ to do that, i have made that mistake so many times! ngill July 21, 2000, 9:11pm 3

  15. c

    The "idea" is an implication of your argument; more so than the implication you drew from mine. And again, the OP returning des was a result of confusion, so when eliminating confusion it would make sense to eliminate the return, which is now pointless.

  16. Visual Studio C++ warning C4829: Possibl

    It has been a very long time since I wrote C++. I have the latest VS 2022 community installed. When I do my build, I get the warning " warning C4829: Possibly incorrect parameters to function main. Consider 'int main (Platform::Array<Platform::String^>^ argv)' ". This is the main function definition. 1.

  17. Memory Supervision System / Bugs / #23 Borland Warnings in init.c

    W8060 Possibly incorrect assignment This warning is generated when the compiler encounters an assignment operator as the main operator of a conditional expression (part of an if, while, or do-while statement).

  18. W8060 Possibly incorrect assignment (C++)

    Go Up to Compiler Errors And Warnings (C++) Index (Command-line option to suppress warning: -w-pia) This warning is generated when the compiler encounters an assignment operator as the main operator of a conditional expression (part of an if, while, or do-while statement).

  19. Macron gambles on snap election after crushing loss to French far right

    An Élysée source close to Macron, who asked to remain anonymous, told CNN the predicted results showed there is a "republican majority" in France made up of those who "don't agree with ...

  20. c

    This is a bit tricky. There's a nice overview of "effective" operator precedence in C and I'll cite the notes from there explaining your problem *):There is a part of the grammar that cannot be represented by a precedence table: an assignment-expression is not allowed as the right hand operand of a conditional operator, so e = a < d ? a++ : a = d is an expression that cannot be parsed, and ...

  21. Powder kegs: 50 years ago, 10-cent beers helped turn a Cleveland

    After Dodgers take 2 of 3 games from Yankees, a World Series matchup seems possible "It kind of fit in with the times," said former Cleveland manager Mike Hargrove, who was a 24-year-old rookie first baseman with the Rangers. "They had Disco Demolition Night in Chicago, and to me it was almost a sign of what was to come 50 years later ...

  22. Why would you use an assignment in a condition?

    The reason is: Performance improvement (sometimes) Less code (always) Take an example: There is a method someMethod() and in an if condition you want to check whether the return value of the method is null. If not, you are going to use the return value again. If(null != someMethod()){. String s = someMethod();