What Does the Underscore in a Function Declaration Do

What does the underscore in a function declaration do?

The underscore means that parameter name should be omitted when calling the function.

So this function:

func webViewDidFinishLoad(_ playerWebView: UIWebView) { /* ... */ }

should be called as:

webViewDidFinishLoad(aWebView)

and this one:

func webViewDidFinishLoad(playerWebView: UIWebView) { /* ... */ }

as:

webViewDidFinishLoad(playerWebView: aWebView)

In Swift, those are seen as two different functions and that's why you don't see the function being called when you change its signature.

More information can be found here, under "Function Argument Labels and Parameter Names":

https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/
Functions.html#//apple_ref/doc/uid/TP40014097-CH10-ID166

What does underscore as an argument in C mean?

The underscore _ is a valid, ordinary identifier. Defining a function like this:

type function(arg1, arg2, arg3)
{
...
}

(i.ee without parameter types) is a deprecated style back from the pre-ANSI days called a K&R-style definition. All parameters implicitly have type int unless you explicitly declare them to have a different type like this:

type function(arg1, arg2, arg3)
type arg1;
type arg2;
type arg3;
{
...
}

where type arg1; is an ordinary declaration. These definitions are still allowed but deprecated. Because you didn't explicitly declare _, the compiler warns you about the implicit declaration as int.

Why do I need underscores in swift?

There are a few nuances to different use cases, but generally an underscore means "ignore this".


When declaring a new function, an underscore tells Swift that the parameter should have no label when called — that's the case you're seeing. A fuller function declaration looks like this:

func myFunc(label name: Int) // call it like myFunc(label: 3)

"label" is an argument label, and must be present when you call the function. (And since Swift 3, labels are required for all arguments by default.) "name" is the variable name for that argument that you use inside the function. A shorter form looks like this:

func myFunc(name: Int) // call it like myFunc(name: 3)

This is a shortcut that lets you use the same word for both external argument label and internal parameter name. It's equivalent to func myFunc(name name: Int).

If you want your function to be callable without parameter labels, you use the underscore _ to make the label be nothing/ignored. (In that case you have to provide an internal name if you want to be able to use the parameter.)

func myFunc(_ name: Int) // call it like myFunc(3)

In an assignment statement, an underscore means "don't assign to anything". You can use this if you want to call a function that returns a result but don't care about the returned value.

_ = someFunction()

Or, like in the article you linked to, to ignore one element of a returned tuple:

let (x, _) = someFunctionThatReturnsXandY()

When you write a closure that implements some defined function type, you can use the underscore to ignore certain parameters.

PHPhotoLibrary.performChanges( { /* some changes */ },
completionHandler: { success, _ in // don't care about error
if success { print("yay") }
})

Similarly, when declaring a function that adopts a protocol or overrides a superclass method, you can use _ for parameter names to ignore parameters. Since the protocol/superclass might also define that the parameter has no label, you can even end up with two underscores in a row.

class MyView: NSView {
override func mouseDown(with _: NSEvent) {
// don't care about event, do same thing for every mouse down
}
override func draw(_ _: NSRect) {
// don't care about dirty rect, always redraw the whole view
}
}

Somewhat related to the last two styles: when using a flow control construct that binds a local variable/constant, you can use _ to ignore it. For example, if you want to iterate a sequence without needing access to its members:

for _ in 1...20 { // or 0..<20
// do something 20 times
}

If you're binding tuple cases in a switch statement, the underscore can work as a wildcard, as in this example (shortened from one in The Swift Programming Language):

switch somePoint { // somePoint is an (Int, Int) tuple
case (0, 0):
print("(0, 0) is at the origin")
case (_, 0):
print("(\(somePoint.0), 0) is on the x-axis")
case (0, _):
print("(0, \(somePoint.1)) is on the y-axis")
default:
print("(\(somePoint.0), \(somePoint.1)) isn't on an axis")
}

One last thing that's not quite related, but which I'll include since (as noted by comments) it seems to lead people here: An underscore in an identifier — e.g. var _foo, func do_the_thing(), struct Stuff_ — means nothing in particular to Swift, but has a few uses among programmers.

Underscores within a name are a style choice, but not preferred in the Swift community, which has strong conventions about using UpperCamelCase for types and lowerCamelCase for all other symbols.

Prefixing or suffixing a symbol name with underscore is a style convention, historically used to distinguish private/internal-use-only symbols from exported API. However, Swift has access modifiers for that, so this convention generally is seen as non-idiomatic in Swift.

A few symbols with double-underscore prefixes (func __foo()) lurk in the depths of Apple's SDKs: These are (Obj)C symbols imported into Swift using the NS_REFINED_FOR_SWIFT attribute. Apple uses that when they want to make a "more Swifty" version of an (Obj)C API — for example, to make a type-agnostic method into a generic method. They need to use the imported API to make the refined Swift version work, so they use the __ to keep it available while hiding it from most tools and documentation.

What is the meaning of an Underscore in javascript function parameter?

The underscore symbol _ is a valid identifier in JavaScript, and in your example, it is being used as a function parameter.

A single underscore is a convention used by some javascript programmers to indicate to other programmers that they should "ignore this binding/parameter". Since JavaScript doesn't do parameter-count checking the parameter could have been omitted entirely.

This symbol is often used (by convention again) in conjunction with fat-arrow functions to make them even terser and readable, like this:

const fun = _ => console.log('Hello, World!')
fun()

In this case, the function needs no params to run, so the developer has used the underscore as a convention to indicate this. The same thing could be written like this:

const fun = () => console.log('Hello, World!')
fun()

The difference is that the second version is a function with no parameters, but the first version has a parameter called _ that is ignored. These are different though and the second version is safer, if slightly more verbose (1 extra character).

Also, consider a case like

arr.forEach(function (_, i) {..})

Where _ indicates the first parameter is not to be used.

The use of underscores like this can get very confusing when using the popular lodash or underscore libraries.

What is the underscore _ in JavaScript?

This is convention of private methods and variables. In JavaScript there is no real privacy of classes.

It means that you should not use these method (starting with "_") out of your object. Of course technically you can, but "_" means that you should not.

Why do some functions in C have an underscore prefix?

The underscore prefix is reserved for functions and types used by the compiler and standard library. The standard library can use these names freely because they will never conflict with correct user programs.

The other side to this is that you are not allowed to define names that begin with an underscore.

Well, that is the gist of the rule. The actual rule is this:

  • You cannot define any identifiers in global scope whose names begin with an underscore, because these may conflict with hidden (private) library definitions. So this is invalid in your code:

    #ifndef _my_header_h_
    #define _my_header_h_ // wrong
    int _x; // wrong
    float _my_function(void); // wrong
    #endif

    But this is valid:

    #ifndef my_header_h
    #define my_header_h // ok
    int x; // ok
    float my_function(void) { // ok
    int _x = 3; // ok in function
    }
    struct my_struct {
    int _x; // ok inside structure
    };
    #endif
  • You cannot define any identifiers in any scope whose names begin with two underscores, or one underscore followed by a capital letter. So this is invalid:

    struct my_struct {
    int _Field; // Wrong!
    int __field; // Wrong!
    };
    void my_function(void) {
    int _X; // Wrong!
    int __y; // Wrong!
    }

    But this is okay:

    struct my_struct {
    int _field; // okay
    };
    void my_function(void) {
    int _x; // okay
    }

There are actually a few more rules, just to make things complicated, but the ones above are the most often violated and the easiest to remember.

Why do some functions have underscores __ before and after the function name?

From the Python PEP 8 -- Style Guide for Python Code:

Descriptive: Naming Styles


The following special forms using leading or trailing underscores are
recognized (these can generally be combined with any case convention):

  • _single_leading_underscore: weak "internal use" indicator. E.g. from M import * does not import objects whose name starts with an underscore.

  • single_trailing_underscore_: used by convention to avoid conflicts with Python keyword, e.g.

    Tkinter.Toplevel(master, class_='ClassName')

  • __double_leading_underscore: when naming a class attribute, invokes name mangling (inside class FooBar, __boo becomes _FooBar__boo; see below).

  • __double_leading_and_trailing_underscore__: "magic" objects or attributes that live in user-controlled namespaces. E.g. __init__,
    __import__ or __file__. Never invent such names; only use them as documented.

Note that names with double leading and trailing underscores are essentially reserved for Python itself: "Never invent such names; only use them as documented".

Is it necessary to use underscore (_) variable inside functions in Dart?

What if the underscore variable is used inside a function?

Dart's official style guide expressly advises against doing that (emphasis mine):

There is no concept of “private” for local variables, parameters, or library prefixes. When one of those has a name that starts with an underscore, it sends a confusing signal to the reader. To avoid that, don’t use leading underscores in those names.

As for the other question in your post:

Is it necessary to use declare an underscored variable in a function(not in a class) to denote that the variable is only used in the function?

No, all variables declared inside a function are naturally limited in-scope to that function. Adding an annotation to say a local is "private" is both redundant and incorrect (as locals aren't "private" because locals aren't shared).

void sample() {
var _something = getSomething();
doSomethingWith(_something);
//use _something
}

In this example, _something is not actually "shared" because doSomethingWith is passed a copy of _something: it doesn't have a reference or pointer to _something.

What is _, (underscore comma) in a Go declaration?

It avoids having to declare all the variables for the returns values.

It is called the blank identifier.

As in:

_, y, _ := coord(p)  // coord() returns three values; only interested in y coordinate

That way, you don't have to declare a variable you won't use: Go would not allow it. Instead, use '_' to ignore said variable.

(the other '_' use case is for import)

Since it discards the return value, it is helpful when you want to check only one of the returned values, as in "How to test key existence in a map?" shown in "Effective Go, map":

_, present := timeZone[tz]

To test for presence in the map without worrying about the actual value, you can use the blank identifier, a simple underscore (_).

The blank identifier can be assigned or declared with any value of any type, with the value discarded harmlessly.

For testing presence in a map, use the blank identifier in place of the usual variable for the value.

As Jsor adds in the comments:

"generally accepted standard" is to call the membership test variables "ok" (same for checking if a channel read was valid or not)

That allows you to combine it with test:

if _, err := os.Stat(path); os.IsNotExist(err) {
fmt.Printf("%s does not exist\n", path)
}

You would find it also in loop:

If you only need the second item in the range (the value), use the blank identifier, an underscore, to discard the first:

sum := 0
for _, value := range array {
sum += value
}

What is the meaning of single and double underscore before an object name?

Single Underscore

In a class, names with a leading underscore indicate to other programmers that the attribute or method is intended to be be used inside that class. However, privacy is not enforced in any way.
Using leading underscores for functions in a module indicates it should not be imported from somewhere else.

From the PEP-8 style guide:

_single_leading_underscore: weak "internal use" indicator. E.g. from M import * does not import objects whose name starts with an underscore.

Double Underscore (Name Mangling)

From the Python docs:

Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, so it can be used to define class-private instance and class variables, methods, variables stored in globals, and even variables stored in instances. private to this class on instances of other classes.

And a warning from the same page:

Name mangling is intended to give classes an easy way to define “private” instance variables and methods, without having to worry about instance variables defined by derived classes, or mucking with instance variables by code outside the class. Note that the mangling rules are designed mostly to avoid accidents; it still is possible for a determined soul to access or modify a variable that is considered private.

Example

>>> class MyClass():
... def __init__(self):
... self.__superprivate = "Hello"
... self._semiprivate = ", world!"
...
>>> mc = MyClass()
>>> print mc.__superprivate
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: myClass instance has no attribute '__superprivate'
>>> print mc._semiprivate
, world!
>>> print mc.__dict__
{'_MyClass__superprivate': 'Hello', '_semiprivate': ', world!'}


Related Topics



Leave a reply



Submit